I have the following code
public interface Data {}
@FunctionalInterface
public interface Handler<T> {
void handle(T data);
}
public record PData() implements Data {
// some fields
}
public abstract class PHandler implements Handler<Data> {
@Override
public void handle(Data data) {
if(data instanceof PData pData) {
//do something with pData
}
}
}
public class SomeProcess {
private Map<Class<?>, Handler<? super Data>> handlers = new HashMap<>();
public SomeProcess() {
//some constructing process
handlers.put(PData.class, new PHandler() {
//here is actually the concrete class of PHandler
});
}
public void someProcessing(Optional<Data> possiblySomeData) {
possiblySomeData.ifPresent(someData -> handlers.get(someData.getClass()).handle(someData));
}
}
My question is, in the abstract class PHandler
, I have to check using instanceOf
. Ideally it shouldn’t need to check, i.e the PHandler should implement Handler<PData>
. However I can’t make it work even if the handlers
in class SomeProcess
is using Handler<? extends Data>
.
How can I have PHandler implements Handler<PData>
?