首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Groovyc成功编译无效的groovy脚本

Groovyc成功编译无效的groovy脚本
EN

Stack Overflow用户
提问于 2013-01-24 17:29:07
回答 1查看 214关注 0票数 2
代码语言:javascript
复制
c:\>cat invalid.groovy
com.test.build(binding)

c:\junk>groovyc invalid.groovy

c:\junk>ls invalid.class
invalid.class

为什么这不会导致编译错误?没有这样的方法com.test.build!

在什么情况下,这种编译会成功?

EN

回答 1

Stack Overflow用户

发布于 2013-01-24 17:41:52

因为Groovy是动态的,所以它不能知道在运行时没有com.test.build

com可以是稍后在代码执行时添加到绑定中的对象

举个例子:

假设我们在Script.groovy中有一点groovy

代码语言:javascript
复制
com.test.build( binding )

用groovyc编译:

代码语言:javascript
复制
groovyc Script.groovy

然后,保留Script.class文件,去掉groovy脚本,以确保我们使用的是类文件:

代码语言:javascript
复制
rm Script.groovy

现在,假设我们在Runner.groovy中有以下内容

代码语言:javascript
复制
// 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()

这将打印:

代码语言:javascript
复制
build called with parameter groovy.lang.Binding@7bf35647

如您所见,它获取com对象(上图)的test参数,并使用绑定作为参数调用build闭包...

希望这是有意义的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14497920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档