In groovy when comparing this and a reference passed in a method: same instance, different metaclass

StackOverflow https://stackoverflow.com/questions/18497466

  •  26-06-2022
  •  | 
  •  

Frage

In groovy 1.8.6, I was trying to do something like 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 for class: groovy.lang.MetaClassImpl

After a bit of trying, I found that passing a reference to self to the method did work. So, basically what I came up with was this:

class Greeter {
    def sayHello(self) {
        assert this == self
        // assert this.metaClass == self.metaClass

        self.metaClass.greeting = { System.out.println "Hello!" }
        greeting()
    }
}

def greeter = new Greeter()
greeter.sayHello(greeter)

The strangest thing is that the assert this == self actually passes, which means they are the same instance... right? The default toString also seems to confirm this.

On the other hand, the 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 is self.metaClass wrapped in a HandleMetaClass, while this.metaClass isn't? Also, how can the first example be made to work without passing in a reference to self?

War es hilfreich?

Lösung 2

You can implement methodMissing in the class as below to answer your 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 that == in groovy actually means equals() (that is value comparison) if you want to compare identity then is() can be used like

a.is(b) //Corresponds to == in Java
a == b //Corresponds to equals() in Java

UPDATE
Can use metaClass as below

Greeter.metaClass.greeting = { println "Hello"}
def greet = new Greeter()

//or
//greet.metaClass.greeting = { println "Hello"}

greet.sayHello()

Andere Tipps

I figured out the 2 questions:

  • groovy.lang.MissingPropertyException: No such property: greeting for class: groovy.lang.MetaClassImpl

  • why this.metaClass == self.metaClass

See this link: https://stackoverflow.com/a/45407488/42769

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top