Search code examples
javacode-generationjavacjava-compiler-api

Java 8 Compiler Plugin : How to add super() call in a constructor?


I'm writing a Java compiler plugin to add a simple class named MyClass in some classes of my project (something like lombok does). I've managed to do it by writing the code bellow (you can find the overall code is here):

TreeMaker maker = TreeMaker.instance(context);
Names symbolsTable = Names.instance(context);

//...

JCTree.JCMethodDecl constructor = maker.MethodDef(maker.Modifiers(Flags.PUBLIC),
        symbolsTable.init,
        null,
        List.nil(), // params
        List.nil(),
        List.nil(),
        maker.Block(0, List.of(callSuper)),
        null
);

JCTree.JCClassDecl myClass = maker
        .at(((JCTree) node).pos)
        .ClassDef(maker.Modifiers(Flags.PUBLIC | Flags.STATIC | Flags.FINAL),
                symbolsTable.fromString("MyClass"),
                List.nil(),
                maker.Ident(symbolsTable.fromString("AnotherClass")),
                List.nil(),
                List.of(constructor)
        );

((JCTree.JCClassDecl) node).defs = ((JCTree.JCClassDecl) node).defs.append(myClass);

I don't know how to write the callSuper statement to get this output :

public static final MyClass extends AnotherClass {
   public MyClass () {
      super(); // I want this line
   }
}

Any help is appreciated.


Solution

  • The callSuper statement is written like the following :

    JCTree.JCMethodInvocation superMethod = maker.Apply(List.nil(), maker.Ident(symbolsTable._super), List.nil());
    JCTree.JCExpressionStatement callSuper = maker.Exec(superMethod); 
    

    and then use it in the constructor :

    JCTree.JCMethodDecl constructor = maker.MethodDef(maker.Modifiers(Flags.PUBLIC),
            symbolsTable.init,
            null,
            List.nil(),
            List.nil(),
            List.nil(),
            maker.Block(0, List.of(callSuper)),
            null
    );