Here is my AST transformation
@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)
}
}
}
When I compile I get this error
[groovyc] General error during class generation: Cannot use return statement with an expression on a method that returns void
How do I build code then that returns void? Thanks.
I've never used the AstBuilder
so I can't help you there. I would guess that the problem is that the AST builder supports Groovy style implicit returns and defaults to returning Object, or something like that?
Here's an example of building a println method call statement with the AST builder code directly. I'm honestly not 100% sure whether or not this also ends up doing a return. But I'm assuming that raw statements built with the low level AST syntax doesn't add implicit returns. There's a separate class for making return statements - ReturnStatement
. So give it a try :)
Statement useMethodBody = new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("this"),
new ConstantExpression("println"),
new ArgumentListExpression(
new ConstantExpression(">>useMethodBody")
)
)
)
Then change useMethodBody[0]
to useMethodBody
. Hopefully it'll work, but I haven't actually tested this so there might be errors :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.