开发者

How to get Class for generic type?

How开发者_Go百科 can I create a Class that represents a generic object?

List<String> list = new List<String>();
Class c1 = list.class;
Class c2 = Class.forName(???); // <- how?
assert c1 == c2;


A class object is not specific to the particular class that is satisfying its type parameter:

assert (new ArrayList<String>()).getClass() == (new ArrayList<Integer>()).getClass();

It's the exact same object regardless of how it's typed.


You can not, since generic information is not present during runtime, due to type erasure.

Your code can be written like:

List<String> list = new ArrayList<String>();
Class c1 = list.getClass();
Class c2 = Class.forName("java.util.ArrayList");
System.out.println(c1 == c2); // true


Class does not represent general types. The appropriate type to use is java.lang.reflect.Type, in particular ParameterizedType. You can get these objects via reflection or make your own.

(Note, generics is a static-typing feature so isn't really appropriate for runtime objects. Static typing information happens to be kept in class files and exposed through the reflection API on reflective objects.)


This worked for me: (Class<List<MYTYPE>>) Class.forName("java.util.ArrayList")

So for your case:

List<String> list = new List<String>();
Class c1 = list.class;
Class c2 = (Class<List<String>>) Class.forName("java.util.ArrayList")
assert c1 == c2;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜