Groovy 定义返回void的AST转换
这是我的AST转换Groovy 定义返回void的AST转换,groovy,Groovy,这是我的AST转换 @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) public class ASTExampleTransformation implements ASTTransformation { public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { astNodes.findAll {
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class ASTExampleTransformation implements ASTTransformation {
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
astNodes.findAll {
node -> node instanceof ClassNode
}.each {
classNode ->
println("classNode")
def useMethodBody = new AstBuilder().buildFromCode {
println(">>useMethodBody")
}
def useMethod = new MethodNode (
'useMethod', ACC_PUBLIC, ClassHelper.VOID_TYPE, [] as Parameter[], [] as ClassNode[], useMethodBody[0]
)
classNode.addMethod(useMethod)
}
}
}
当我编译时,我得到了这个错误
[groovyc] General error during class generation: Cannot use return statement with an expression on a method that returns void
如何构建返回void的代码?谢谢 我从未使用过
AstBuilder
,因此我无法在这方面帮助您。我猜问题在于AST构建器支持Groovy风格的隐式返回,默认为返回对象,或者类似的东西
下面是一个直接使用AST生成器代码构建println方法调用语句的示例。老实说,我不能100%确定这是否也会带来回报。但我假设使用低级AST语法构建的原始语句不会添加隐式返回。有一个单独的类用于生成返回语句-ReturnStatement
。所以试试看:)
然后将useMethodBody[0]
更改为useMethodBody
。希望它能工作,但我还没有实际测试过,所以可能会有错误:)
Statement useMethodBody = new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("this"),
new ConstantExpression("println"),
new ArgumentListExpression(
new ConstantExpression(">>useMethodBody")
)
)
)