可能重复:
如何抑制特定函数的 Java 编译器警告
我想使用地图来实现策略模式。但是,我找不到一种可以很好地与泛型配合使用的方法。是否可以在不更改功能的情况下从以下代码中删除编译警告?
import java.util.HashMap;
import java.util.Map;
interface Event
{
}
interface EventProcessor<T extends Event>
{
public void handleEvent(T event);
}
class EventA implements Event
{
}
class EventB implements Event
{
}
class ProcessorA implements EventProcessor<EventA>
{
@Override
public void handleEvent(final EventA event)
{
System.out.println("Handling event type A");
}
}
class ProcessorB implements EventProcessor<EventB>
{
@Override
public void handleEvent(final EventB event)
{
System.out.println("Handling event type B");
}
}
class GenericEventProcessor
{
Map<Class<? extends Event>, EventProcessor> map = new HashMap<Class<? extends Event>, EventProcessor>();
public GenericEventProcessor()
{
map.put(EventA.class, new ProcessorA());
map.put(EventB.class, new ProcessorB());
}
public void processEvent(Event event)
{
EventProcessor eventProcessor = map.get(event.getClass());
//Java Warning: GenericEventProcessorTest.java uses unchecked or unsafe operations.
eventProcessor.handleEvent(event);
}
}
public class GenericEventProcessorTest
{
public static void main(String[] args)
{
EventA eventA = new EventA();
EventB eventB = new EventB();
GenericEventProcessor eventProcessor = new GenericEventProcessor();
eventProcessor.processEvent(eventA);
eventProcessor.processEvent(eventB);
}
}
编辑:我应该说,不使用 SuppressWarnings!这通常告诉我我的设计有问题,我想知道这里是否是这种情况。