Groovyc成功编译了无效的groovy脚本
为什么这不会导致编译错误?没有这样的方法com.test.buildGroovyc成功编译了无效的groovy脚本,groovy,Groovy,为什么这不会导致编译错误?没有这样的方法com.test.build 在什么情况下编译会成功?由于Groovy是动态的,它无法知道在运行时不会有com.test.build com可能是在代码执行的稍后日期添加到绑定的对象 例如: 假设我们在Script.groovy c:\>cat invalid.groovy com.test.build(binding) c:\junk>groovyc invalid.groovy c:\junk>ls invalid.class
在什么情况下编译会成功?由于Groovy是动态的,它无法知道在运行时不会有
com.test.build
com
可能是在代码执行的稍后日期添加到绑定的对象
例如: 假设我们在
Script.groovy
c:\>cat invalid.groovy
com.test.build(binding)
c:\junk>groovyc invalid.groovy
c:\junk>ls invalid.class
invalid.class
rm Script.groovy
用groovyc编译它:
com.test.build( binding )
然后,保留Script.class
文件,扔掉groovy脚本以确保我们使用的是类文件:
groovyc Script.groovy
现在,假设我们在Runner.groovy
c:\>cat invalid.groovy
com.test.build(binding)
c:\junk>groovyc invalid.groovy
c:\junk>ls invalid.class
invalid.class
rm Script.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()
如您所见,它获取com
对象(上面的映射)的test
参数,并使用绑定作为参数调用build
闭包
希望这是有意义的…谢谢,如果我添加了“com.test.build”jar,那么如果我执行所述文件,我可能无法运行,正如我所说,它可能正在等待一个名为com
的对象,谢谢,我对这部分感到困惑“可能正在等待一个名为com的对象”你能解释一下吗,什么是动态的then@anish添加了一个示例。。。希望它有意义——如果没有,请告诉我,我将尝试用另一种方式来解释我的意思:-)谢谢,这是有意义的,但是如果我们将所需的jar文件添加到这个类中,那么会发生什么呢。