我创造了转型
package org.global
import groovy.transform.CompileStatic
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.ast.ClassNode
import org.codehaus.groovy.ast.ClassHelper
import org.codehaus.groovy.ast.MethodNode
import org.codehaus.groovy.ast.Parameter
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.expr.VariableExpression
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.expr.ArgumentListExpression
@CompileStatic
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class SayHelloTransformation implements ASTTransformation {
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
BlockStatement statement = new BlockStatement()
statement.addStatement(
new ExpressionStatement (
new MethodCallExpression (
new VariableExpression("this"),
new ConstantExpression("println"),
new ArgumentListExpression(
new ConstantExpression("hello world")
)
)
)
)
MethodNode sayHelloMethod = new MethodNode(
"sayHello", 0x0001, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY, statement
)
sourceUnit.AST.methods.add(sayHelloMethod)
}
}
我编译了它。然后我添加了带有描述符
的META-INF
文件夹
org.global.SayHelloTransformation
所以整体结构看起来像这样
META-INF\
services\
org.codehaus.groovy.transform.ASTTransformation
org\
global\
SayHelloTransformation.class
SayHelloTransformation.groovy
然后我将SomeClass.groovy
添加到与SayHelloTransformation.groovy
class SomeClass {
}
和test.groovy
档案
new SomeClass()。sayHello()
但我得到了这个例外
Caught: groovy.lang.MissingMethodException: No signature of method: SomeClass.sayHello() is applicable for argument types: (
) values: []
groovy.lang.MissingMethodException: No signature of method: SomeClass.sayHello() is applicable for argument types: () values
: []
at test.run(test.groovy:2)
整个结构看起来像这样
META-INF\
services\
org.codehaus.groovy.transform.ASTTransformation
org\
global\
SayHelloTransformation.class
SayHelloTransformation.groovy
SomeClass.class
SomeClass.groovy
test.groovy