Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

java - Access generic type parameter at runtime?

Event dispatcher interface

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

Implementation

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");
}

}

Usage

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

        }
    });
    removeEventListener(l);

I've marked two errors with a comment above (in the implementation). Is there any way to get runtime access to this information?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you can't refer 'T' at runtime.

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

update
But something like this would achieve similar effect

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);
}

And to create listener

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...