标签:
项目路径:http://git.oschina.net/ellipse/ASTSample/tree/howtodebug
1、先创建一个ASTTransformation
package myast import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.transform.GroovyASTTransformation /** * Created by Misty on 2015/4/30. * * 注解用来指定转换的时机 */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) class MyASTTransformation implements ASTTransformation { @Override void visit(ASTNode[] nodes, SourceUnit source) { println("MyASTTransformation visit() $nodes") } }2、为局部ASTTransformation创建一个注解
package myast import org.codehaus.groovy.transform.GroovyASTTransformationClass import java.lang.annotation.Documented import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target /** * Created by Misty on 2015/4/30. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target([ElementType.FIELD, ElementType.TYPE]) @GroovyASTTransformationClass("myast.MyASTTransformation") @interface MyAST { }3、一个调用ASTTransformation的测试类
package myast /** * Created by Misty on 2015/4/30. */ @MyAST class Person { }到此为止,一个简单的ASTTransformation就完成了,但直接调用Person是看不到输出的
package myast /** * Created by Misty on 2015/4/30. */ class FailMyASTTest { static def main(args) { new Person() // 看不到输出 } }
4、重头戏在这里,GroovyClassLoader发威了
package myast /** * Created by Misty on 2015/4/30. */ class MyASTTest { static def main(args) { def parent = MyASTTest.classLoader def loader = new GroovyClassLoader(parent) def gclass = loader.parseClass(new File("src/main/groovy/myast/Person.groovy")) } }此时在控制台输出
MyASTTransformation visit() [org.codehaus.groovy.ast.AnnotationNode@491666ad, myast.Person]
标签:
原文地址:http://my.oschina.net/u/580483/blog/408400