jastrachan | 5 Apr 09:05 2005
Picon

Re: Closures and listeners

On 4 Apr 2005, at 17:43, Martin C. Martin wrote:
> Thanks James,
>
> jastrachan@... wrote:
>> On 2 Apr 2005, at 17:33, Martin C. Martin wrote:
>>> Hi all,
>>>
>>> Is there an easy way to create a listener using a closure, outside  
>>> of a builder?  In Java I'd do this:
>>>
>>> Processor deviceProc = ...
>>> deviceProc.addControllerListener(new ControllerListener() {
>>>    public void controllerUpdate(ControllerEvent ce) {
>>>       ...
>>>    }
>>> }
>>>
>>> What's the groovy way?
>> deviceProc.controllerUpdate = { ce -> println "I was just called with  
>> event $ce" }
>> i.e. we use the javabeans introspector to make event listener methods  
>> available as properties which can be set with a closure
>
> Our of curiosity, how does it know that the listener interface is  
> ControllerListener?  Does it look for any member function of the form  
> addXXX(Type), then look for methods of Type?  Does type need to be an  
> interface?  Does the "addXXX" function need to be named after the type  
> of it's argument (i.e. addFoo(Foo) is treated as a listener, but  
> addFoo(Bar) isn't)?

Yes - its using the Java Beans introspector (java.beans.Introspector)  
which will look for a BeanInfo for your bean or create one using its  
own naming conventions. (See the Java Beans spec for details of the  
naming conventions it uses if you don't provide your own BeanInfo  
class). We're not performing any naming conventions ourselves - the  
standard Java Bean introspector does that for us.

Basically we get the BeanInfo for a bean and expose its  
EventSetDescriptors as properties (assuming there is no clash with  
regular beans).

http://java.sun.com/j2se/1.4.2/docs/api/java/beans/ 
EventSetDescriptor.html

Its actually the EventSetDescriptor.getListenerMethods() which we  
expose as a writable property which you can assign to a closure...

http://java.sun.com/j2se/1.4.2/docs/api/java/beans/ 
EventSetDescriptor.html#getListenerMethods()

James
-------
http://radio.weblogs.com/0112098/


Gmane