Groovy 1.8中可以在编译时为脚本添加Customizer,之前已经介绍了ImportCustomizer的用法。Hubert Klein Ikkink又发布了一则窍门:使用ASTTransformationCustomizer透明的为脚本添加AST Transformation。
AST Transformation有局部和全局之分(详细解释,请参见本站的《Groovy Transformation:Global Transformation》)。对于局部Transformation,只需要使用注解即可,而对于全局的Transformation,则需要将ASTTransformationCustomizer添加至CompilerConfiguration对象,如:
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
import org.codehaus.groovy.control.CompilerConfiguration
import groovy.util.logging.Log
def conf = new CompilerConfiguration()
//这里我们使用ASTTransformationCustomizer添加了@Log
conf.addCompilationCustomizers(new ASTTransformationCustomizer(Log))
def shell = new GroovyShell(conf)
//对于shell中的代码,均可以使用Log
shell.evaluate("""
class Car {
Car() {
log.info 'Car constructed'
}
}
log.info 'Constructing a car'
def c = new Car()
""")
......
关于文中的详细示例代码,请参见原文。关于更多的Groovy窍门,参见Groovy Goodness。

最新评论
9 周 6 小时之前
9 周 1 天之前
11 周 5 天之前
11 周 5 天之前
17 周 2 天之前
17 周 4 天之前
19 周 3 天之前
20 周 1 天之前
20 周 2 天之前
20 周 5 天之前