In groovy when comparing this and a reference passed in a method: same instance, different metaclass -
in groovy 1.8.6, trying this:
class greeter { def sayhello() { this.metaclass.greeting = { system.out.println "hello!" } greeting() } } new greeter().sayhello()
this didn't work:
groovy.lang.missingpropertyexception: no such property: greeting class: groovy.lang.metaclassimpl
after bit of trying, found passing reference self method did work. so, came this:
class greeter { def sayhello(self) { assert == self // assert this.metaclass == self.metaclass self.metaclass.greeting = { system.out.println "hello!" } greeting() } } def greeter = new greeter() greeter.sayhello(greeter)
the strangest thing assert == self
passes, means same instance... right? default tostring
seems confirm this.
on other hand, assert this.metaclass == self.metaclass
fails:
assert this.metaclass == self.metaclass | | | | | | | org.codehaus.groovy.runtime.handlemetaclass@50c69133[groovy.lang.metaclassimpl@50c69133[class greeter]] | | greeter@1c66d4b3 | false groovy.lang.metaclassimpl@50c69133[class greeter]
why self.metaclass wrapped in handlemetaclass, while this.metaclass isn't? also, how can first example made work without passing in reference self?
you can implement methodmissing
in class below answer last question:
class greeter { def sayhello() { //this.metaclass.greeting = { system.out.println "hello!" } greeting() goodnight() } def methodmissing(string name, args){ if(name == 'greeting'){ println "hello!" } else println "good night" } } new greeter().sayhello()
also note ==
in groovy means equals()
(that value comparison) if want compare identity is()
can used like
a.is(b) //corresponds == in java == b //corresponds equals() in java
update
can use metaclass below
greeter.metaclass.greeting = { println "hello"} def greet = new greeter() //or //greet.metaclass.greeting = { println "hello"} greet.sayhello()
Comments
Post a Comment