RealmSpy
RealmSpy

Reputation: 355

Java reference to a method that takes a subclass of another class

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

Answers (2)

mattmess1221
mattmess1221

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

Louis Wasserman
Louis Wasserman

Reputation: 198311

Well, you can't just listen to any Event, only to HelloEvents.

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

Related Questions