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.JCClassDecl myClass = maker
.at(((JCTree) node).pos)
.ClassDef(maker.Modifiers(Flags.PUBLIC | Flags.STATIC | Flags.FINAL),
symbolsTable.fromString("MyClass"),
List.nil(),
null, // replace Here by ?
List.nil(),
List.nil()
);
((JCTree.JCClassDecl) node).defs = ((JCTree.JCClassDecl) node).defs.append(myClass);
The code before will generate :
public static class MyClass {
}
Now, I want MyClass
to extend another parametrized class :
public static class MyClass extends AnotherClass<Param1, Param2>{
}
I don't know how to do it !
All I know it is to change the 4th parameter of the ClassDef
method from null
to a JCExpression
.
Any help is appreciated.
The extends expression :
JCTree.JCIdent extendClassName = maker.Ident(symbolsTable.fromString("AnotherClass"));
ListBuffer<JCTree.JCExpression> extendsParams = new ListBuffer<>();
extendsParams.add(maker.Ident(symbolsTable.fromString("Param1")));
extendsParams.add(maker.Ident(symbolsTable.fromString("Param2")));
JCTree.JCTypeApply extend = maker.TypeApply(extendClassName, extendsParams.toList());
The best documentation I've found is the lombok project