这是我的GORM对象
@UpdatedProperties
class Cart {
Date lastUpdated
Date dateCreated
String name
}
这是注释定义:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@GroovyASTTransformationClass(["UpdatedPropertiesASTTransformation"])
public @interface UpdatedProperties {
}
这是AST的定义
@GroovyASTTransformation(phase = CompilePhase.CLASS_GENERATION)
class UpdatedPropertiesASTTransformation implements ASTTransformation{
//...
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
astNodes.findAll { node -> node instanceof ClassNode}.each {
classNode ->
def testMethodBody = new AstBuilder().buildFromString (
"""
println(">>*************myMethod)";
"""
)
def myMethod = new MethodNode('myMethod', ACC_PUBLIC, ClassHelper.VOID_TYPE, [] as Parameter[], [] as ClassNode[], testMethodBody[0])
classNode.addMethod(myMethod)
}
}
...
}
当我尝试调用该方法时,我得到:
groovy.lang.MissingMethodException:方法的无签名:Cart.myMethod()适用于参数类型:()值:[]
任何提示表示赞赏。谢谢
最佳答案
类生成太晚了,无法在其中向类添加方法的编译阶段,因此您需要将编译阶段更改为语义分析或规范化。 (无论如何,这可能比您想要添加方法要晚得多。Groovy Compile Phase Guide)
您的AST字符串中还有两个问题。您的println中存在语法错误,println(">>*************myMethod)";
应该读为println(">>*************myMethod");
,并且您需要添加一个明确的return;
语句,因为您要返回void
(否则Groovy将在方法的末尾添加一个return null;
,这将与您的方法冲突void
返回类型)。
关于grails - 无法使用AST转换将方法添加到GORM对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28284258/