I'm working on a program that need to react to different custom events and listeners.
I'm trying to make it short using generics, the fact is, I don't understand where is my mistake.
Here my code :
The listeners and the event :
public interface MyFirstListener extends EventListener {
void firstRequest(String text);
}
public interface MySecondListener extends EventListener {
void secondRequest(String text);
}
public class MyEvent extends EventObject {
private String text = null;
public MyEvent(Object source, String text) {
super(source);
this.text = text;
}
public String getText() {
return text;
}
}
And here the tricky code :
public class MyProblem {
private EventListenerList listenerList = new EventListenerList();
public MyProblem() {}
public <T extends EventListener> void addListener(T listener) {
listenerList.add(T.class, listener); // Here I have : Illegal class literal for the type parameter T
}
public <T extends EventListener> void removeListener(T listener) {
listenerList.remove(T.class, listener); // Here I have : Illegal class literal for the type parameter T
}
void fireFirstRequestEvent(MyEvent evt) {
for (MyFirstListener listener : listenerList.getListeners(MyFirstListener.class)) {
listener.firstRequest(evt.getText());
}
}
void fireSecondRequestEvent(MyEvent evt) {
for (MySecondListener listener : listenerList.getListeners(MySecondListener.class)) {
listener.secondRequest(evt.getText());
}
}
public static void main(String[] args) {
FirstClass first = new FirstClass();
SecondClass second = new SecondClass();
MyProblem problem = new MyProblem();
problem.addListener(first);
problem.addListener(second);
}
}
class FirstClass implements MyFirstListener {
@Override
public void firstRequest(String text) {
// Do Something
}
}
class SecondClass implements MySecondListener {
@Override
public void secondRequest(String text) {
// Do Something
}
}
The problem is in the methods addListeners and removeListeners, I have this error : Illegal class literal for the type parameter T I don't get the trick to catch it.
I try also this code :
listenerList.add(listener.getClass(), listener); // Here I have : The method add(Class<T>, T) in the type EventListenerList is not applicable for the arguments (Class<capture#1-of ? extends EventListener>, T)
I try some other thing without result and I don't find any solution that match my code.
Anybody have any solution or it is unsolvable ? My goal is to have the shorter code possible and even pretty.
Thank's