groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ruben Laguna <>
Subject Is it possible to add GroovyObject methods via a category?
Date Thu, 07 Dec 2017 09:31:56 GMT
In the Groovy in Action book, chapter 8.4.5 says "Category method
names can well take the form of property accessors (pretending
property access), operator methods, and GroovyObject methods. MOP hook
methods cannot be added through a category class. This is a
restriction as of Groovy 2.4. The feature may become available in
later versions."

It interpreted this as meaning that I can add getProperty,
getMetaClass, invokeMethod to a class using categories but not
methodMissing or propertyMissing.

But when I tried to add invokeMethod using a category the change has no effect

class MyClass{}

a = new MyClass()

class MyCategory {
    def missingMethod(String name, def args) { "missingMethod" } //
GINA says no MOP hook method

    def invokeMethod(String name, def args) { "invokeMethod" } // but
GroovyObject method should be fine
    def getProperty(String name) { "missingProperty" }

    def getMyProperty() { "prop1" }

use(MyCategory) {
    assert "missingMethod" == a.missingMethod('a', 'b') // methods are the
    assert "invokeMethod" == a.invokeMethod('a', 'b')
    assert "prop1" == a.myProperty

    // but they are not in effect
    // assert "missingMethod" == a.method1() // MissingMethodException
    // assert "invokeMethod" == a.method2()  // MssingMethodException
    // assert "missingProperty" == // MissingPropertyException

Is is possible or not?


View raw message