Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

Not able to dynamically add method to Groovy using metaClass from within instance

I'm afraid I'm a beginner in Groovy so this might be very silly. (using groovy 2.3.4) I have the following code:

class Test {

    public void method() {
        def methodName = "dynamicMethodName"
        this.metaClass."$methodName" = {->}
        this."${methodName}"()
    }
}

new Test().method()

Running this will throw the following error:

Caught: groovy.lang.MissingPropertyException: No such property: dynamicMethodName for class: groovy.lang.MetaClassImpl
    groovy.lang.MissingPropertyException: No such property: dynamicMethodName for class: groovy.lang.MetaClassImpl
at Test.method(what.groovy:5)
at Test$method.call(Unknown Source)
at what.run(what.groovy:10)

Can someone help me figure out what I am doing wrong? I also tried not being 'too dynamic' and altered the code like so:

class Test {

    public void method() {
        this.metaClass.dynamicMethodName = {->}
        this.dynamicMethodName()
    }
}

new Test().method()

But I still get the same error

UPDATE

It seems that if I add the method outside the class by using an instance reference instead of using this, it works.

Is there no way to dynamically add methods for an instance from within the instance itself?

Upvotes: 2

Views: 761

Answers (1)

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

It turns out, if the class extends the class Expando, it works.

Answer found here: https://stackoverflow.com/a/7079038/56242

Upvotes: 1

Related Questions