GroovyInterceptable&;引入属性

GroovyInterceptable&;引入属性,groovy,Groovy,我有一个实现GroovyInterceptable的类,我认为它应该使所有方法调用都通过“invokeMethod”。但我发现事实并非如此 class Test implements GroovyInterceptable{ String name @Override Object invokeMethod(String name, Object args) { def metaMethod = this.metaClass.getMetaMethod

我有一个实现GroovyInterceptable的类,我认为它应该使所有方法调用都通过“invokeMethod”。但我发现事实并非如此

class Test implements GroovyInterceptable{

    String name

    @Override
    Object invokeMethod(String name, Object args) {
        def metaMethod = this.metaClass.getMetaMethod(name, args)
        return metaMethod.invoke(this, "BAR")
    }

    public static void main(String[] args) {
        Test.metaClass.NEWATTRIBUTE = null

        def test = new Test()
        test.NEWATTRIBUTE = "MEOW1"
        println test.NEWATTRIBUTE   // shouldnt this be BAR ?


        test.setNEWATTRIBUTE("MEOW2")
        println test.NEWATTRIBUTE // prints 'BAR'


        // much simpler example ....

        test.name = "MOOO"
        println test.name // shouldnt this be BAR ?

        test.setName("MOOO")
        println test.name // prints 'BAR'
    }
}
我想我在什么地方读到过

test.NEWATTRIBUTE = "MEOW1"
不能直接访问字段。Groovy仍然会调用setter方法,因此应该调用invokeMethod,不是吗

谢谢


Alex

设置属性时,Groovy调用
setProperty
。将此方法添加到类:

void setProperty(String prop, val) {
    System.out.println "set property $prop with $val"
}

威尔普:非常感谢。以下是完整的代码:

class Test implements GroovyInterceptable{

    String name

    @Override
    Object invokeMethod(String name, Object args) {
        def metaMethod = this.metaClass.getMetaMethod(name, args)
        return metaMethod.invoke(this, "BAR")
    }

    void setProperty(String prop, val) {
        getMetaClass().setProperty(this, prop, "BAR2");
    }

    public static void main(String[] args) {
        Test.metaClass.NEWATTRIBUTE = null

        def test = new Test()
        test.NEWATTRIBUTE = "MEOW1"
        println test.NEWATTRIBUTE   // prints BAR2


        test.setNEWATTRIBUTE("MEOW2")
        println test.NEWATTRIBUTE // prints BAR


        test.name = "MOOO"
        println test.name // prints BAR2

        test.setName("MOOO")
        println test.name // prints BAR
    }
}
事实证明,无论类是否实现了
GroovyInterceptable
,都会调用
setProperty()
。但是
invokeMethod()
仅在类实现
GroovyInterceptable