java 如何获取泛型类型的类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5030148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:06:56  来源:igfitidea点击:

How to get Class for generic type?

java

提问by yegor256

How can I create a Classthat represents a generic object?

如何创建一个Class代表通用对象的对象?

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

回答by Mark Peters

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.

不管它是如何输入的,它都是完全相同的对象。

回答by Mark Peters

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

回答by Tom Hawtin - tackline

Classdoes 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.

Class不代表一般类型。要使用的适当类型java.lang.reflect.Type尤其是ParameterizedType. 您可以通过反射获取这些对象或创建自己的对象。

(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.)

(注意,泛型是一种静态类型特性,因此并不真正适合运行时对象。静态类型信息恰好保存在类文件中,并通过反射对象上的反射 API 公开。)

回答by pcampana

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

这对我有用: (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;