grails - 无法使用AST转换将方法添加到GORM对象

标签 grails groovy gorm abstract-syntax-tree

这是我的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/

相关文章:

grails - Grails,Cucumber,Geb和Spring Security无法正常工作

grails - 如何以编程方式设置gradle依赖项

java - 如何使用泰坦 API?

android - Gradle 总是从最后一个 flavor 中的 buildType 中获取值

grails - 域类上的Grails动态查找器方法在插件项目中不可见

grails - 在具有域继承的Grails GORM中,是否可以通过查询父类(super class)来找到特定的子类实例

grails - 从Grails中的select标签中选择多个值

java - 将整个目录内容复制到另一个目录?

hibernate - 如何在grails中使用executeQuery()进行多态查询?

grails - 更新数据库记录