The problem is that Listener<Foo>
and Listener<Bar>
are really the exact same interface, due to generic type erasure. So this isn't possible (AFAIK).
Is it possible to have an indefinite number of type parameters in Java?
-
02-06-2022 - |
Question
I'm making an event system in Java and I've run into a problem in writing the Listener part.
This is my current Listener
class:
public interface Listener<E extends Event<?>> {
public void handleEvent(E event);
}
I want to keep it expandable in a way that I can have one Listener class that can be flexible to any Event type, i.e. Listener<Foo>
and Listener<Bar>
instead of FooListener
and BarListener
, but I also want implementing classes to be able to listen to multiple events.
My problem is that a class cannot implement the Listener class with two different type parameters.
public class MultiListener implements Listener<Foo>, Listener<Bar> {
// does not work
}
I know it's possible for a method to have an indefinite number of parameters, like this:
public void toInfinityAndBeyond(String... lotsOfStrings) {
}
But can my Listener
class have an indefinite number of type parameters to listen to multiple events?
public class MultiListener implements Listener<ThisEvent, ThatEvent, AnotherEvent> {
// hypothetical
}
Solution
OTHER TIPS
I don't fully understand generics, but I've found they tend to make Java, a statically typed language, a lot more static. This can be a good thing. But what you are trying to do is rather dynamic.
So in this case I would dump the generics. Make Foo and Bar extend or implement Event. (Event with no "<>".) Make sure the Event class has enough methods that the code in Listener's handleEvent() doesn't need multiple if
's using instanceof
; so it can just deal with plain Event objects. (Mind, the occasional instanceof
won't hurt anything, usually.)