Groovy AST转换 - 替换方法 [英] Groovy AST Transformation - replace method
问题描述
我首先检查方法是否存在,然后删除它(基于此)。
MethodNode methodNode = parentClass.getMethod(methodName,Parameter.EMPTY_ARRAY)
if(methodNode!= null){
parentClass.getMethods()。remove(methodNode)
}
我看到大小改变的集合,但该方法仍然可以在类节点上访问。
删除该方法后,我想添加一个新的相同名称:
parentClass.addMethod(newMethodNode)
但是,这会导致以下错误:
方法'grails的重复方法名称/签名.plugin.Bar getBar()'在'grails.plugin.Foo'类中。
执行此操作的正确方法是什么?
更新:
因为我打算做的只是替换方法的现有功能,我反而创建了一个新的块语句,并使用 methodNode.setCode(语句)在现有方法上设置
。
听起来像你想要做的是用一些其他东西?这是一个在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
新的ExpressionStatement(
新的MethodCallExpression(
myVar,myMethod,新的ArgumentListExpression()
)
)
))
return methodBody
}
除此之外,我无法提供帮助,因为我从未实际尝试删除方法:)
I am trying to replace a method of a class using AST transformations.
I first check to see if the method exists and then remove it (based on this).
MethodNode methodNode = parentClass.getMethod(methodName, Parameter.EMPTY_ARRAY)
if (methodNode != null) {
parentClass.getMethods().remove(methodNode)
}
I see the size change on the collection, but the method is still accessible on the class node.
After removing the method I would then like to add a new one of the same name:
parentClass.addMethod(newMethodNode)
However, this causes the following error:
Repetitive method name/signature for method 'grails.plugin.Bar getBar()' in class 'grails.plugin.Foo'.
What is the correct way to do this?
Update:
Since all I was intending to do was replace existing functionality of the method, I instead created a new block statement and set this on the existing method using methodNode.setCode(statement)
.
Sounds like what you're trying to do is to wrap a method with some other stuff? Here's an example of wrapping a method in a 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
}
Other than that I'm not able to help since I've never actually attempted to remove a method before :)
这篇关于Groovy AST转换 - 替换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!