我有以下方法:
public <T> T get(String property, Class<T> expectedClass) {...}
当我尝试用泛型类代替T
对其进行分类时,我无法使用 .class
获取类对象语法(如 ArrayList<Object>.class
)。 Java 不是应该将泛型简化为普通类吗?因此,不应该有某种方法来获取 .class 对象吗?
这是实际的方法调用:
itemSource = (Collection<Item<SourceIdentifierType>>) configuration.get("initial items", KeyCollection<Item<SourceIdentifierType>>.class);
最佳答案
Java 语言规范对 class literals 有如下规定:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type (§4.3), is Class.
[...]
It is a compile-time error if the named type is a type variable (§4.4) or a parameterized type (§4.5) or an array whose element type is a type variable or parameterized type.
你不能这样做。
你可以做的,但你必须大量重构,是使用 type tokens .
关于java - 泛型的 .class 语法中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428879/