You don't need generics to accomplish this. Simply use the interface name as your type:
public void registerNewInput(String name, InputType typeHandler)
{
inputHandlers.put(name, typeHandler);
}
public void handleInput(String handlerName, String input)
{
InputType handler = (InputType) inputHandlers.get(handlerName);
handler.handleInput(input);
}
The reason you don't need generics here is because Java types can always be assigned to a variable of a more general type. I.e. - if Circle
extends Shape
, then a Circle
can be assigned to a reference of type Shape
:
Shape s = new Circle(); // works just fine
So in this example, it allows you to declare your parameter as type InputType
and pass anything that implements InputType
when calling the method.
Additionally, you can save yourself a cast by parameterizing your map
private Map<String, InputType> inputHandlers;
public void registerNewInput(String name, InputType typeHandler)
{
inputHandlers.put(name, typeHandler);
}
public void handleInput(String handlerName, String input)
{
InputType handler = inputHandlers.get(handlerName); // no cast needed here
handler.handleInput(input);
}