Java 8 编译器插件:如何在构造函数中添加 super() 调用?
Java 8 Compiler Plugin : How to add super() call in a constructor?
我正在编写一个 Java 编译器插件,以在我的项目的某些 class 中添加一个名为 MyClass
的简单 class(类似于 lombok)。我已经设法通过编写下面的代码来做到这一点(你可以发现整体代码是 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);
我不知道如何编写 callSuper
语句来获得此输出:
public static final MyClass extends AnotherClass {
public MyClass () {
super(); // I want this line
}
}
感谢任何帮助。
callSuper
语句的写法如下:
JCTree.JCMethodInvocation superMethod = maker.Apply(List.nil(), maker.Ident(symbolsTable._super), List.nil());
JCTree.JCExpressionStatement callSuper = maker.Exec(superMethod);
然后在构造函数中使用它:
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
);
我正在编写一个 Java 编译器插件,以在我的项目的某些 class 中添加一个名为 MyClass
的简单 class(类似于 lombok)。我已经设法通过编写下面的代码来做到这一点(你可以发现整体代码是 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);
我不知道如何编写 callSuper
语句来获得此输出:
public static final MyClass extends AnotherClass {
public MyClass () {
super(); // I want this line
}
}
感谢任何帮助。
callSuper
语句的写法如下:
JCTree.JCMethodInvocation superMethod = maker.Apply(List.nil(), maker.Ident(symbolsTable._super), List.nil());
JCTree.JCExpressionStatement callSuper = maker.Exec(superMethod);
然后在构造函数中使用它:
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
);