c:\>cat invalid.groovy
com.test.build(binding)
c:\junk>groovyc invalid.groovy
c:\junk>ls invalid.class
invalid.class
これがコンパイルエラーにならないのはなぜですか? そのようなメソッド com.test.build はありません!
このコンパイルはどのようなシナリオで成功しますか?
c:\>cat invalid.groovy
com.test.build(binding)
c:\junk>groovyc invalid.groovy
c:\junk>ls invalid.class
invalid.class
これがコンパイルエラーにならないのはなぜですか? そのようなメソッド com.test.build はありません!
このコンパイルはどのようなシナリオで成功しますか?
com.test.build
Groovyは動的であるため、実行時に存在しないことを知ることはできません。
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
し、バインディングをパラメーターとしてクロージャーを呼び出します...
これが理にかなっていることを願っています...