[英]Class object of generic class (java)
java中有没有办法获取类似Class<List<Object>>
的实例?
怎么样
(Class<List<Object>>)(Class<?>)List.class
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);
Because of type erasure, at the Class level, all List interfaces are the same.由于类型擦除,在 Class 级别,所有 List 接口都是相同的。 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>
作为类型,其中List.class
属于该类型,但您无法获得更具体的信息,因为它们不是单独的类,只是被编译器删除的类型声明为显式铸件。
As mentioned in other answers, Class
represents an erased type.正如其他答案中提到的, Class
代表一种擦除类型。 To represent something like ArrayList<Object>
, you want a Type
.要表示类似ArrayList<Object>
,您需要一个Type
。 An easy way of getting that is:一个简单的方法是:
new ArrayList<Object>() {}.getClass().getGenericSuperclass()
The generic type APIs introduced in 1.5 are relatively easy to find your way around. 1.5 中引入的泛型类型 API 相对容易找到。
You could use Jackson's ObjectMapper
你可以使用杰克逊的ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, ElementClass.class)
No unchecked warnings, no empty List instances floating around.没有未经检查的警告,没有空的 List 实例。
List.class
特定类型的泛型在编译时被“擦除”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.