Groovy invokeMethod add method to metaclass if this statement?

I noticed strange behavior with MetaClass Groovy, and I am wondering if anyone can let me know what is going on here.

This works great:

@Override
Object invokeMethod(String name, Object args) {
    if(true) {
        println("Should only see this once")
        def impl = { Object theArgs -> println("Firing WeirdAction") }
        getMetaClass()."$name" = impl
        return impl(args)
    }
}

However, if I remove the if statement, it throws a MissingPropertyException:

@Override
Object invokeMethod(String name, Object args) {
    println("Should only see this once")
    def impl = { Object theArgs -> println("Firing WeirdAction") }
    getMetaClass()."$name" = impl
    return impl(args)
}

Here is my class instance and call, the class is empty except for the method definition above.

IfTester sut = new IfTester()
sut.WeirdAction()

Does anyone have an idea that I don't understand here?

+4
source share
1 answer

Using Groovy 2.4.5, the problem seems to be related getMetaClass()to compared IfTester.getMetaClass(). Consider:

class IfTester {

    @Override
    Object invokeMethod(String name, Object args) {
        if (true) {
        println "Should only see this once"
        def impl = { def theArgs -> println "Firing WeirdAction" }
        def mc1 = getMetaClass()
        println "mc1: " + mc1
        println "----"
        def mc2 = IfTester.getMetaClass()
        println "mc2: " + mc2
        IfTester.getMetaClass()."$name" = impl
        return impl(args)
        }
    }
} 

IfTester sut = new IfTester()
sut.WeirdAction()

if(true), mc1 mc2 , . if, mc1 .

, . , , this .

+1

Source: https://habr.com/ru/post/1652517/


All Articles