[Note: I have looked at all the possible duplicates - none are direct duplicates and none provide an answer to this specific question.]
I want to create a factory for event handlers, where the event handler's generic type parameter is the event type. The event type is only known at runtime.
In code, this is an illustration of what I want to achieve:
public interface Event {
}
public interface EventHandler<T extends Event> {
void handle(T event);
}
public class EventHandlerFactory {
public <T extends Event> EventHandler<T> getHandler(Class<T> eventType) {
return ... // implementation?
}
}
And then be able to consume the events in a type safe way, like so:
Event event = getEvent("some json representation");
factory.getHandler(event.getClass()).handle(event);
Any ideas how I can achieve this (or even something similar if this is not possible)?
Edit:
A concrete event handler might look like this:
public class JobCreatedEventHandler implements EventHandler<JobCreatedEvent>
{
@Override
public void handle(JobCreatedEvent event) {
...
}
}