I came across the below groovy script code in a book. And that gave rise to some weird results for me.
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()
it is output as follows:
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:
So I'm very confused:
- why is this.metaClass not equal to instance.metaClass?
- Also, I cannot use this.metaClass to introduce new methods; groovy tells me that this.metaClass does not have the property that I wanted to introduce.
- What does "org.codehaus.groovy.runtime.HandleMetaClass@245b4bdc [groovy.lang.MetaClassImpl @ 245b4bdc [Person]] mean" mean? I know that "245b4bdc" can be a pointer to an object. But why does HandleMetaClass and MetaClassImpl have the same pointer value "245b4bdc"?
Currently, I realized that @ 245b4bdc is not an " object reference ", so HandleMetaClass @ 245b4bdc is not necessarily the same instance as MetaClassImpl @ 245b4bdc . We can use the Object.is () method to determine if they are the same. (I did it, the result is false )
metaclass this groovy
Guocheng
source share