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);
}
}