0

Is it possible in Java to have a composite object dynamically forward events to its children. He is example of what I'm trying to achieve:

public interface Listener {
    void onEvent();
    void onAnotherEvent();
    ...
}

List<Listener> listenerList;
Listener listener = // some listener implementation that forwards methods to all Listeners in listenerList

The main problem is that I want this to by dynamic. Otherwise, I could just make a subclass myself that has a list of children and forwards all the events. I have considered using a dynamic proxy, but I wanted to see if there is perhaps a better and more efficient option in Java.

---Edit---

Here is my best attempt. It works but is a bit limited.

public final class DynamicCompositionWrapper<T>
{
    private final T       parent;
    private final List<T> children;


    public DynamicCompositionWrapper(Class<T> cls)
    {
        children = new LinkedList<T>();

        @SuppressWarnings("unchecked")
        T temp = (T)Proxy.newProxyInstance(cls.getClassLoader(), new Class<?>[] {cls}, new InvocationHandler()
        {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable
            {
                for (T t : children)
                {
                    method.invoke(t, args);
                }
                return null;
            }
        });
        parent = temp;
    }


    public T getParent()
    {
        return parent;
    }


    public void addChild(T t)
    {
        children.add(t);
    }
}
Steven Roberts
  • 300
  • 1
  • 3
  • 14
  • Define "children." If you mean subclasses, then no, there isn't. If you mean something else, please elaborate fully. Your question is unclear. – markspace Oct 30 '14 at 01:18
  • Yes, by children I meant subclasses. So one Listener is composed of multiple Listener implementations/subclasses. I would like to call a method on the parent Listener and have method calls forwarded to the multiple children listeners. – Steven Roberts Oct 30 '14 at 01:34
  • So, generally you can't. You can maybe make some final method in the super class that a user must call that does the work, but without some weird extra-linguistic stuff (Aspect oriented programming maybe? Not sure) you can't. – markspace Oct 30 '14 at 01:41

0 Answers0