Search code examples
javaintellij-ideapluginsgenerate

IntelliJ Plugin - How to automatic generate Code Snippet [Java]


I am currently working on a project that is realized via an IntelliJ plugin. Unfortunately I can't find an example/guide how to set up the function for "automatic code generation".

An example would be the getter/setter methods of IntelliJ. (Alt + insert)

I would like to use "my Plugin" to build a small Java method in the current file.

It would be nice if someone would give me a tip or even a code example.

I am aware of the general structure -(plugin.xml -> group-id="GenerateGroup" etc.)


Solution

  • Okay, I still haven't found a real tutorial ...

    My solution:

    1. Add/Change <depends>com.intellij.modules.java</depends> in your plugin.xml

    2. When you use a gradle project add: intellij { plugins 'java' in your build.gradle

    This is just my version of a new constructor

        public void actionPerformed(AnActionEvent e)
        {
    
            WriteCommandAction.runWriteCommandAction(null, new Runnable() {
                @Override
                public void run() {
                  Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
    
                    Project project = e.getData(CommonDataKeys.PROJECT);
                    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    
                    PsiJavaFile psiJavaFile = (PsiJavaFile)file;
                    PsiClass[] classes = psiJavaFile.getClasses();
    
                    PsiClass psiClass = classes[0];
    
                    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
                    PsiMethod newConstructor = factory.createMethodFromText("puplic " + psiClass.getName() + "() {//new Constructor }", psiClass);
                    final PsiMethod[] psiMethods = psiClass.getMethods();
                    PsiMethod firstMethod = (psiMethods.length == 0) ? null : psiMethods[0];
                    psiClass.addBefore(newConstructor, firstMethod);
                }
            });}
    

    Maybe someone could take a look at it and suggest improvements