2
c:\>cat invalid.groovy
com.test.build(binding)

c:\junk>groovyc invalid.groovy

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

これがコンパイルエラーにならないのはなぜですか? そのようなメソッド com.test.build はありません!

このコンパイルはどのようなシナリオで成功しますか?

4

1 に答える 1

0

com.test.buildGroovyは動的であるため、実行時に存在しないことを知ることはできません。

comコードの実行後日、バインディングに追加されたオブジェクトである可能性があります


例:

中にこのちょっとしたグルーヴィーがあるとしましょうScript.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

ご覧のとおりtest、オブジェクトのパラメーターcom(上のマップ)を取得buildし、バインディングをパラメーターとしてクロージャーを呼び出します...

これが理にかなっていることを願っています...

于 2013-01-24T09:41:51.617 に答える