我正在尝试使用AST转换替换类的方法。
我首先检查方法是否存在,然后将其删除(based on this)。
MethodNode methodNode = parentClass.getMethod(methodName, Parameter.EMPTY_ARRAY)
if (methodNode != null) {
parentClass.getMethods().remove(methodNode)
}
我看到集合的大小发生了变化,但仍然可以在类节点上访问该方法。
删除方法后,我想添加一个同名的新方法:
parentClass.addMethod(newMethodNode)
但是,这会导致以下错误:
Repetitive method name/signature for method 'grails.plugin.Bar getBar()' in class 'grails.plugin.Foo'.
这样做的正确方法是什么?
更新
由于我打算做的只是替换方法的现有功能,我改为创建一个新的block statement并使用methodNode.setCode(statement)
在现有方法上设置它。
答案 0 :(得分:0)
听起来你要做的就是用其他东西包装一个方法?这是一个在try / finally中包装方法的示例。
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.ast.expr.*
import org.codehaus.groovy.ast.stmt.*
methodNode.setCode(methodThatCreatesAst(methodNode.getCode()))
def methodThatCreatesAst(Statement statementToWrap) {
BlockStatement methodBody = new BlockStatement()
methodBody.addStatement(new TryCatchStatement(
// try
statementToWrap,
// finally
new ExpressionStatement(
new MethodCallExpression(
"myVar", "myMethod", new ArgumentListExpression()
)
)
))
return methodBody
}
除此之外,我无法提供帮助,因为我之前从未尝试过删除方法:)