java - 泛型的 .class 语法中断

标签 java class object generics

我有以下方法:

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/

相关文章:

Java特殊字符正则表达式

python - 使 Python 类方法可在 Mongodb 中搜索

php - 面向对象的 PHP 和 MVC : calling a method from another controller?

java - 如何将匿名类(不是实例)作为参数传递给在 Java 中期望类型为类的方法

javascript - 在迭代期间向 JSON 对象添加属性?

c# - 在 C# 中使用 GetType/instanceof 与替代方案

java - 为什么 "java.lang.OutOfMemoryError: Java heap space"没有被抓到?

java - 在构造函数中设置父子关系而不泄漏 "this"变量

java - token 类型取决于以下 token

javascript - 通过名称定位图层后查找图层的索引#