Gmane
Gravatar
From: Guillaume Laforge <glaforge@...>
Subject: Re: generic decorator/proxy
Newsgroups: gmane.comp.lang.groovy.user
Date: 2005-06-16 14:57:55 GMT (4 years, 2 weeks, 5 days, 6 hours and 38 minutes ago)
Hello,

On 16/06/05, Jonathan Carlson <Jonathan.Carlson@...> wrote:
> I just read about a feature in BeanShell and I'm hoping it can be done
> as easily in Groovy.

Sure :-)

> You can write a generic Decorator/Proxy by writing a method called
> invoke(methodName, args[])  Any non-implemented method call gets
> redirected to this method.  It is kind of like the Java Dynamic Proxy
> interface, but with far less hassle and limitations.
> 
> Is this in Groovy?  If not, could it easily be added?

It's been there since the beginning of Groovy, but is probably
"under-documented" :-(
In fact, you've used that feature each time you've used Groovy
builders or POGOs (Plain Old Groovy Objects).

All classes written in Groovy extend GroovyObjectSupport:
http://groovy.codehaus.org/apidocs/groovy/lang/GroovyObjectSupport.html

Notice the invokeMethod() method?

Let's take an example:

class Foo {
    void methodOne() { println "invoked methodOne()" }
    int methodTwo(bar) { println "invoked methodTwo(${bar})"; return 255 }
    def invokeMethod(String methodName, Object params) {
        println "invoked ${methodName}()"
    }
    static void main(args) {
         def f = new Foo()
         f.methodOne()
         def i = f.methodTwo("bar")
         f.inexistantMethod()
    }
}

Execute it, and you'll notice that standard methods are called, and if
a method doesn't exist, it's routed to the invokeMethod() method.

I guess that's what you were looking for?

Many objects in Groovy implement that interface (GroovyObject) or
extend that class (GroovyObjectSupport), like Expandos, builders, or
Proxy, etc...

-- 
Guillaume Laforge
http://glaforge.free.fr/weblog/?catid=2