i have the flowing script:
task myTask {}
class Person {
Person() {
Person instance = this
println this.metaClass.class.name
println this.getMetaClass().class.name
println instance.metaClass.class.name
println instance.getMetaClass().class.name
}
}
Person person = new Person()
And the output is :
groovy.lang.MetaClassImpl
groovy.lang.MetaClassImpl
org.codehaus.groovy.runtime.HandleMetaClass
org.codehaus.groovy.runtime.HandleMetaClass
can anyone explain to me what is going on ?
thanks in advance.
Take a look at this
class
,Take a look at the screenshot of the
groovysh
. It might give you a little hint about what's going on.p
andq
are two different objects, butp.metaClass
is the same asq.metaClass
, andprintAll
prints exactly the same thing for both,p
andq
a.metaClass
andb.metaClass
are holdingthis.class.metaClass
, notthis.metaClass
, you seeThere is only one object created of
MetaClassImpl
, and also only one ofHandleMetaClass
, forPerson
. And no matter how many times you instantiatePerson
, they will be assigned to the instance. But, when you expand any of that instance, only then a newHandleMetaClass
object will be created -- just for that particular object; and this timeHandleMetaClass
will be holding notMetaClassImpl
, butExpandoMetaClass
instead.See the screenshot below,
Now, to answer your question,
this.metaClass
is a special case, likethis
itself. It doesn't give you the handle,HandleMetaClass
object, so you can't expand overmetaClass
ofthis
-- directly; and there is no sense in that either, because then all other future instances will share that expansion.If you really want that behaviour then you can pass
this
to some other variable, i.e.instance = this
, as you did in the constructor, and then you can expand over thatinstance
-- and that expansion would be true forthis
and all other future instances. But then, why not add the behaviour to class itself, in the first place. Why expand?