I don’t understand why the compiler doesn’t accept this code
import javax.swing.event.EventListenerList;
import java.util.EventListener;
public class GenericEventsManager {
EventListenerList listeners = new EventListenerList();
public <T extends EventListener> void addListener(T listener) {
listeners.add(listener.getClass(), listener);
}
}
The error I get is
The method add(Class<T>, T) in the type EventListenerList is not applicable for the arguments (Class<capture#1-of ? extends EventListener>, T)
The argument in addListener is of a type that extends EventListener, so listener.getClass() returns Class<? extends EventListener>, which is exactly what the EventListenerList.add method expects
Can someone explain this? I have a feeling that it has something to do with getClass() not being resolved at compile time but it still doesn’t make sense to me
The compiler simply will not let you do this. As the error message implies, the type parameter on the
Classparameter must be exactly the same as the type of the second argument, which is not true in the code above.Because the return type of
listener.getClass()isClass<? extends EventListener>, notClass<T>. You could — but I do not recommend doing so — cast the returnedClassto make this compile:You’ll get a compiler warning when doing so:
because this is not a (type)safe cast.
The root cause of this might (I’m honestly not sure) be simply poor API design in the declaration of
EventListenerList#add(). Typically PECS is used in this kind of situation; it’s possible there’s a good reason thatadd()is not wildcarded.