java - 如何从参数化参数中获取参数的类型

时间:2012-06-21 07:45:41

标签: java generics

我正试图找到一个解决方案(如果有的话):

public class Generics {
    Map<Class<? extends SomeObject1>, SomeObject2>> map;
    map = new HashMap<Class<? extends SomeObject1>, SomeObject2>>();

    public static <E extends SomeObject1> SomeObject2 get(Class<E> c) {
        if (map.containsKey(c))
           return map.get(c);
        else {
           SomeObject2 o = new SomeObject2();
           map.put(c, o);
           return o;
        }
    }
}
...
//somewhere
public <T extends SomeObject1> void aMethod(AnInterestedClass<T> list) {
    // How to get the value from the map
    // knowing that the key is of type T?
    Generics.get(); 
}

想法?

1 个答案:

答案 0 :(得分:1)

由于type erasure,您只能通过将Class对象传递给aMethod来完成此操作。请参阅this related thread