Reputation: 355
I'm trying to pass a subclass as a parameter to a method. So far I've not been successfull, and even told it's not possible to do in Java. I want the opinion of stackoverflow, and suggestions to make it work.
Let's assume 'HelloEvent' extends 'Event'...
I have a method :
public void addListener(Consumer<? extends Event> consumer) {
[...]
}
and another method :
public void listen(HelloEvent helloEvent) {
[...]
}
I want to do this :
addListener(this::listen);
In IDEA I have the error 'Cannot resolve method listen'. Of course this happens because 'listen' is not exactly an Event, but rather a subclass.
Is there a way to do this? Maybe a work around?
I've tried having it being a Function or replacing 'extends' with 'super' and it does not work. I've been attempting to fix this problem for a few weeks now.
Upvotes: 0
Views: 227
Reputation: 4444
Even if you could do this, you would get a ClassCastException
when the listener is called. However, if you included the type with addListener
, you could add logic to filter that.
void addListener(Consumer<? super Event> listener) {
[...]
}
<T extends Event> void addListener(Class<T> type, Consumer<T> listener) {
addListener(evnt -> {
if (type.isInstance(evnt))
listener.accept(evnt);
});
}
Upvotes: 0
Reputation: 198311
Well, you can't just listen
to any Event
, only to HelloEvent
s.
It should probably be Consumer<? super Event>
, because e.g. What is PECS (Producer Extends Consumer Super)? .
In that case, you could write
addListener(event -> {
if (event instanceof HelloEvent) {
listen((HelloEvent) event);
}
});
...but nothing short of that will work, honestly. You have to check that it's a HelloEvent
explicitly.
Upvotes: 1