c:\>cat invalid.groovy
com.test.build(binding)
c:\junk>groovyc invalid.groovy
c:\junk>ls invalid.class
invalid.class为什么这不会导致编译错误?没有这样的方法com.test.build!
在什么情况下,这种编译会成功?
发布于 2013-01-24 17:41:52
因为Groovy是动态的,所以它不能知道在运行时没有com.test.build
com可以是稍后在代码执行时添加到绑定中的对象
举个例子:
假设我们在Script.groovy中有一点groovy
com.test.build( binding )用groovyc编译:
groovyc Script.groovy然后,保留Script.class文件,去掉groovy脚本,以确保我们使用的是类文件:
rm Script.groovy现在,假设我们在Runner.groovy中有以下内容
// Create a class which you can call test.build( a ) on
class Example {
Map test = [
build : { it ->
println "build called with parameter $it"
}
]
}
// Create one of our Com objects
def variable = new Example()
// Load the Script.class, and make an instance of it
def otherscript = new GroovyClassLoader().loadClass( 'Script' ).newInstance()
// Then, set `com` in the scripts binding to be our variable from above
otherscript.binding.com = variable
// Then, run the script
otherscript.run()这将打印:
build called with parameter groovy.lang.Binding@7bf35647如您所见,它获取com对象(上图)的test参数,并使用绑定作为参数调用build闭包...
希望这是有意义的。
https://stackoverflow.com/questions/14497920
复制相似问题