2010-06-07 7 views
1

이벤트 디스패처 인터페이스런타임시 제네릭 형식 매개 변수에 액세스 하시겠습니까?

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

구현 (구현에) 내가 위의 코멘트와 함께 두 개의 오류를 표시 한

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

     } 
    }); 
    removeEventListener(l); 

public class DefaultEventDispatcher implements EventDispatcher { 

@SuppressWarnings("unchecked") 
private Map<Class, Set<EventListener>> listeners = new HashMap<Class, Set<EventListener>>(); 

public void addSupportedEvent(Class eventType) { 
    listeners.put(eventType, new HashSet<EventListener>()); 
} 

@Override 
public <T> EventListener<T> addEventListener(EventListener<T> l) { 
    Set<EventListener> 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 <T> void removeEventListener(EventListener<T> l) { 
    Set<EventListener> 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"); 
} 

} 

사용. 이 정보에 대한 런타임 액세스 권한을 얻는 방법이 있습니까?

답변

1

아니요, 런타임에 'T'를 참조 할 수 없습니다.

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

갱신
그러나이 같은 성취 것 같은 효과

abstract class EventListener<T> { 
    private Class<T> type; 
    EventListener(Class<T> type) { 
     this.type = type; 
    } 
    Class<T> getType() { 
     return type; 
    } 

    abstract void onEvent(T t); 
} 

그리고 당신은 접근 방식에서 그것을 할 수 없습니다

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

너무 나쁜, 내 깔끔한 이벤트 모델을 간다 –

+0

옵션은 여전히있어, (가 :) 추한 내가 유사한 장애물로 실행했습니다 –

+0

이없는 당신은 적어도 새의 EventListener 을 켤 수 있습니다 String.class)를 형식 유추를 사용하여 새 EventListener (String.class)에 추가하면 형식을 한 번만 선언하면됩니다. –

0

리스너 생성하는 방법 시도 중입니다. erasure입니다. 그러나 디자인을 조금 변경하면 필요한 것을 얻을 수 있다고 생각합니다. 의 EventListener 인터페이스에 다음과 같은 방법을 추가하는 것을 고려 :

public Class<T> getEventClass(); 

모든 EventListener를 구현 그것이 작동 이벤트의 클래스를 명시해야한다 (나는 T는 이벤트 유형을 의미한다고 가정). 이제 addEventListener 메소드에서이 메소드를 호출하고 런타임에 유형을 판별 할 수 있습니다.

관련 문제