我有这个类实现 ASTTransformation 并为每个标有特定注释的字段创建一个 getter 和 setter 方法:
@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
public class Rewriter implements ASTTransformation {
public void visit(ASTNode[] nodes, SourceUnit source) {
List fields = nodes.findAll { it instanceof FieldNode }
fields.each {
MethodNode get = createGetter(it)
MethodNode set = createSetter(it)
source.getAST().addMethod(get)
source.getAST().addMethod(set)
}
}
private MethodNode createGetter(FieldNode f) {
Parameter[] parameters = []
ClassNode[] exceptions = []
Statement state = new AstBuilder().buildFromString("return ${f.name}").get(0)
return new MethodNode("get" + f.name.capitalize(), Opcodes.ACC_PUBLIC, ClassHelper.make(f.getType().name), parameters, exceptions, state)
}
private MethodNode createSetter(FieldNode f) {
Parameter[] parameters = [
new Parameter(ClassHelper.make(f.getType().name), f.name)
]
ClassNode[] exceptions = []
Statement state = new AstBuilder().buildFromString("this.${f.name} = ${f.name}").get(0)
return new MethodNode("set" + f.name.capitalize(), Opcodes.ACC_PUBLIC, ClassHelper.VOID_TYPE, parameters, exceptions, state)
}
}
运行以下测试类
class Main {
@Accessors
int counter = 5
public static void main(String[] args) {
println getCounter()
}
}
产生以下错误:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
User\groovy\meta\src\Main.groovy: -1: Invalid duplicate class definition of class Main : The source User\groovy\meta\src\Main.groovy contains at least two definitions of the class Main.
One of the classes is an explicit generated class using the class statement, the other is a class generated from the script body based on the file name. Solutions are to change the file name or to change the class name.
@ line -1, column -1.
1 error
这是什么原因造成的?它似乎创建了方法并将它们添加到源的 AST 中。我正在使用 Groovy-Eclipse 4.3