泛型类的类对象(java)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1079279/
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
Class object of generic class (java)
提问by
is there a way in java to get an instance of something like Class<List<Object>>
?
java中有没有办法获得类似的实例Class<List<Object>>
?
回答by jwoolard
回答by Jason S
List.class
the specific type of generics is "erased" at compile time.
特定类型的泛型在编译时被“擦除”。
回答by Yishai
Because of type erasure, at the Class level, all List interfaces are the same. They are only different at compile time. So you can have Class<List>
as a type, where List.class
is of that type, but you can't get more specific than that because they aren't seperate classes, just type declarations that are erased by the compiler into explicit casts.
由于类型擦除,在 Class 级别,所有 List 接口都是相同的。它们仅在编译时不同。所以你可以有Class<List>
一个类型, whereList.class
是那种类型,但你不能得到比这更具体的,因为它们不是单独的类,只是被编译器擦除为显式强制转换的类型声明。
回答by Tom Hawtin - tackline
As mentioned in other answers, Class
represents an erased type. To represent something like ArrayList<Object>
, you want a Type
. An easy way of getting that is:
如其他答案中所述,Class
表示已擦除类型。要表示类似的东西ArrayList<Object>
,您需要一个Type
. 一个简单的方法是:
new ArrayList<Object>() {}.getClass().getGenericSuperclass()
The generic type APIs introduced in 1.5 are relatively easy to find your way around.
1.5 中引入的泛型类型 API 相对容易找到。
回答by newacct
how about
怎么样
(Class<List<Object>>)(Class<?>)List.class
回答by Armhart
public final class ClassUtil {
@SuppressWarnings("unchecked")
public static <T> Class<T> castClass(Class<?> aClass) {
return (Class<T>)aClass;
}
}
Now you call:
现在你打电话:
Class<List<Object>> clazz = ClassUtil.<List<Object>>castClass(List.class);
回答by Lorcan O'Neill
You could use Hymanson's ObjectMapper
你可以使用Hyman逊的 ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, ElementClass.class)
No unchecked warnings, no empty List instances floating around.
没有未经检查的警告,没有空的 List 实例。