1

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.

1
  • just that line with ; behind it will do. at least, if there is a default or no-param constructor in that class Commented Apr 24, 2020 at 12:06

1 Answer 1

1

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
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.