我正在尝试创建一个Handler
接口,该接口能够根据其类型处理不同类型的事件。我遇到以下警告时遇到问题:
Unchecked call to 'handle(T)' as a member of raw type 'Handler'
这是我的课程。
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();
}
}
}
输出看起来正确:
String: hello
Integer: 12
Object: 23
我想问题是我的dispatch
方法返回了Handler
未经检查的版本。
不确定正确的做法是什么。
答案 0 :(得分:0)
创建工厂(贷记至Generic Factory With Unknown Implementation Classes)
public class HandlerFactory<H extends Handler> {
final Class<H> handlerClass;
protected HandlerFactory(final Class<H> clazz) {
handlerClass = clazz;
}
protected H create() throws InstantiationException, IllegalAccessException {
H handler = handlerClass.newInstance();
return handler;
}
public static <H extends Handler> HandlerFactory<H> createFactory(final Class<H> clazz) throws InstantiationException, IllegalAccessException {
return new HandlerFactory(clazz);
}
public static Handler dispatch(Object obj) throws InstantiationException, IllegalAccessException {
Class c;
if (obj instanceof String) {
c = StringHandler.class;
} else if (obj instanceof Integer) {
c = IntegerHandler.class;
} else {
c = ObjectHandler.class;
}
HandlerFactory factory = HandlerFactory.createFactory(c);
return factory.create();
}
}
未显示异常处理程序:
...
String a = "hello";
Integer b = 12;
Long c = 23L;
HandlerFactory.dispatch(a).handle(a);
HandlerFactory.dispatch(b).handle(b);
HandlerFactory.dispatch(c).handle(c);