That makes sense. Adapter classes can help here, but what you are describing 
sounds a bit like what you get with delegates in C#.

I was going to add that it took me a long time to appreciate anonymous inner 
classes, and so far the only real use case I have found for them is internal 
event listeners. In fact, I suspect that is why they were originally created, 
since (way back) Java was originally about AWT.

They really are handy in this context because they get around the potential 
memory leak issues associated with hard references. If you attach an anonymous 
inner class instance as a listener and don't maintain a reference to it 
yourself, the listener will be garbage collected with the event source.

BXML listener list elements serve a similar purpose. When you define a listener 
as follows, you are creating something that acts like an anonymous inner class, 
since it can see the other (effectively private) variables declared within the 
page:

<PushButton>
    <buttonPressListeners>
    function buttonPressed(button) {
        ...
    }
    </buttonPressListeners>
<PushButton>

Syntactically, this might be a bit cleaner than an anonymous inner class, but 
the downside is obviously that the script is uncompiled.

G


On Jul 26, 2010, at 7:16 PM, Michael Allman wrote:

> On Mon, 26 Jul 2010, Greg Brown wrote:
> 
>>> nobody likes defining anonymous classes
>> 
>> I like anonymous inner classes. They are great for defining internal event 
>> handlers.
> 
> Ahhh... I'm just referring to using a method instead of a class that defines 
> a single method.  My event listener interface looks like
> 
> public interface EventListener {
>       public void invoke(Event e);
> }
> 
> and my event listener factory looks like
> 
> static MethodEventListener create(Object target, String listenerMethodName) {
>       final Method listenerMethod;
> 
>       try {
>               Class<?> targetClass = target.getClass();
>               listenerMethod = targetClass.getMethod(listenerMethodName, 
> Event.class);
>       } catch (RuntimeException ex) {
>               throw ex;
>       } catch (Exception ex) {
>               throw new RuntimeException(ex);
>       }
> 
>       return new MethodEventListener(target, listenerMethod);
> }
> 
> Cheers,
> 
> Michael

Reply via email to