在运行时访问generics类型参数?

事件调度程序界面

public interface EventDispatcher {  EventListener addEventListener(EventListener l);  void removeEventListener(EventListener l); } 

履行

 public class DefaultEventDispatcher implements EventDispatcher { @SuppressWarnings("unchecked") private Map<Class, Set> listeners = new HashMap<Class, Set>(); public void addSupportedEvent(Class eventType) { listeners.put(eventType, new HashSet()); } @Override public  EventListener addEventListener(EventListener l) { Set lsts = listeners.get(T); // ****** error: cannot resolve T if (lsts == null) throw new RuntimeException("Unsupported event type"); if (!lsts.add(l)) throw new RuntimeException("Listener already added"); return l; } @Override public  void removeEventListener(EventListener l) { Set lsts = listeners.get(T); // ************* same error if (lsts == null) throw new RuntimeException("Unsupported event type"); if (!lsts.remove(l)) throw new RuntimeException("Listener is not here"); } } 

用法

  EventListener l = addEventListener(new EventListener() { @Override public void onEvent(ShapeAddEvent event) { // TODO Auto-generated method stub } }); removeEventListener(l); 

我在上面的评论中标记了两个错误(在实现中)。 有没有办法让运行时访问这些信息?

不,你不能在运行时引用’T’。

http://java.sun.com/docs/books/tutorial/java/generics/erasure.html

更新
但是这样的事情会产生类似的效果

 abstract class EventListener { private Class type; EventListener(Class type) { this.type = type; } Class getType() { return type; } abstract void onEvent(T t); } 

并创造倾听者

 EventListener e = new EventListener(String.class) { public void onEvent(String event) { } }; e.getType(); 

由于擦除 ,您无法在尝试的方法中执行此操作。 然而,随着设计的一些变化,我相信你可以实现你所需要的。 考虑将以下方法添加到EventListener接口:

 public Class getEventClass(); 

每个EventListener实现都必须声明它使用的事件类(我假设T代表一个事件类型)。 现在,您可以在addEventListener方法中调用此方法,并在运行时确定类型。