I'm trying to create a Handler
interface, which is able to handle different types of events based on their types. I'm having trouble with the following warning:
Unchecked call to 'handle(T)' as a member of raw type 'Handler'
Here are my classes.
public interface Handler<T> {
void handle(T event); }
public class IntegerHandler implements Handler<Integer> {
@Override
public void handle(Integer event) {
System.out.println("Integer: " + event);
}
}
public class ObjectHandler implements Handler<Object> {
@Override
public void handle(Object event) {
System.out.println("Object: " + event);
}
}
public class StringHandler implements Handler<String> {
@Override
public void handle(String event) {
System.out.println("String: " + event);
}
}
public class TestHandlers {
public static void main(String[] args) {
String a = "hello";
Integer b = 12;
Long c = 23L;
dispatch(a).handle(a);
dispatch(b).handle(b);
dispatch(c).handle(c);
}
private static Handler dispatch(Object o) {
if (o instanceof String) {
return new StringHandler();
} else if (o instanceof Integer) {
return new IntegerHandler();
} else {
return new ObjectHandler();
}
}
}
The output looks correct:
String: hello
Integer: 12
Object: 23
I guess the problem is that my dispatch
method is returning a unchecked version of Handler
.
Not sure what the proper way is to do this right.