开发者

How do you get an instance of java.lang.Class for a generic collection like Collection<SomeObject>?

How do you get an instance of开发者_开发百科 java.lang.Class for a generic collection like Collection<SomeObject>?

I'm looking for something like the following:

Class clazz = Collection<SomeObject>.class;


You can't. Type erasure means that you can't do this this way.

What you can do is:

  1. declare a field of the generic type.
  2. call the reflection API to get a Type. E.g. Field.getGenericType().
  3. Use the Type API to see the parameter.


As others said, the types are erased at runtime. You must provide the class object to your method. Assuming all your classes that extend SomeObject have constructors with no parameters, you can create objects using reflection. Example:

public <T extends SomeObject> Collection<T> getObjects(Class<T> clazz) {
    List<T> result = new ArrayList<T>();
    for(int i=0; i<3; i++) {
        try {
            T t = clazz.getConstructor((Class[]) null).newInstance((Object[]) null);
            // do something with t
            result.add(t);
        } catch (Exception e) {
            // handle exception
        }
    }
    return result;
}

If you have a class that extends SomeObject, you can use the method like this:

class ObjA extends SomeObject {
}

Collection<ObjA> collection = getObjects(ObjA.class);


At runtime these types are erased. If you take an instance of Collection and call getClass(), you will simply get the Collection class.

There are other reflection APIs to get information about members declared with a type parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜