我在书中遇到了下面的groovy脚本代码.它给我带来了一些奇怪的输出.
class Person{ def work(){ println "work()" } def sports=['basketball','football','voleyball'] def methodMissing(String name, args){ if(name in sports){ println "injected ${name} into Person class" Person instance=this println "this.metaClass:\t\t${this.metaClass}" println "instance.metaClass:\t${instance.metaClass}" assert this.metaClass==instance.metaClass }else{ println "no such method:${name}() in Person class" } } } def jack=new Person() jack.football()
它的输出如下:
injected football into Person class this.metaClass: groovy.lang.MetaClassImpl@245b4bdc[class Person] instance.metaClass: org.codehaus.groovy.runtime.HandleMetaClass@245b4bdc[groovy.lang.MetaClassImpl@245b4bdc[class Person]] Caught: Assertion failed: //I did not paste the detailed assertion here for simplicity
所以我很困惑:
为什么this.metaClass不等于instance.metaClass?
更进一步,我不能使用this.metaClass来注入新方法; groovy告诉我this.metaClass没有这样的属性,我打算注入.
"org.codehaus.groovy.runtime.HandleMetaClass@245b4bdc [groovy.lang.MetaClassImpl@245b4bdc [class Person]]"是什么意思?我知道"245b4bdc"可能是对象指针.但是为什么HandleMetaClass和MetaClassImpl具有相同的指针值"245b4bdc"?
目前,我发现@ 245b4bdc不是" 对象引用 ",因此HandleMetaClass @ 245b4bdc不一定与MetaClassImpl @ 245b4bdc相同.我们可以使用Object.is()方法来判断它们是否相同.(我这样做,结果是假的)