java - 如何调用泛型对象的静态类方法?

标签 java class generics robospice

我需要将泛型类型的类传递给类的构造函数。类(class)是SpiceRequest来自 RoboSpice用于引用构造函数的 Android 库。

类需要将泛型的类传递给构造函数似乎很奇怪,而它可以从泛型类型本身访问,在本例中为 RESULT.class ,但也许我错了。无论如何,我不想更改库的代码,而是需要为 SpiceRequest 的泛型类型使用泛型类型。 , Map<String, ? extends Object> .这是我的代码:

SpiceRequest<Map<String, ? extends Object>> request =
        new SpiceRequest<Map<String, ? extends Object>>(???) {
            ...
        };

以及SpiceRequest的签名构造函数:

public SpiceRequest(final Class<RESULT> clazz) {
    ...
}

为了???我试过Map.class编译器错误:The constructor SpiceRequest<Map<String,? extends Object>>(Class<Map>) is undefined.

Map<String, ? extends Object>.class给出错误:Syntax error on tokens, PrimitiveType expected instead , 特别强调 ? extends Object .它还会给出与 Map.class 相同的错误.

Map.<String, ? extends Object>class也给出相同的编译器错误。

获取通用类的正确方法是什么Class<Map<String, ? extends Object>>

最佳答案

具体参数化类型或通配符参数化类型没有类文字。来自 Angelika Langer's generics tutorial :

Wildcard parameterized types lose their type arguments when they are translated to byte code in a process called type erasure. As a side effect of type erasure, all instantiations of a generic type share the same runtime representation, namely that of the corresponding raw type. In other words, parameterized types do not have type representation of their own. Consequently, there is no point to forming class literals such as List<?>.class , List<? extends Number>.class and List<Long>.class, since no such Class objects exist. Only the raw type List has a Class object that represents its runtime type. It is referred to as List.class.

出于同样的原因,没有具体参数化类型的类字面量,简而言之就是 type erasure .

为了您的目的,您只需要对类文字进行未经检查的转换:

Class<Map<String, ?>> c = (Class<Map<String, ?>>)(Class<?>)Map.class;

请注意,通过 Class<?> 双重转换是必要的,因为从 Class<Map> 直接转换至 Class<Map<String, ?>>是非法的。

关于java - 如何调用泛型对象的静态类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419269/

相关文章:

将列表列表传递给 Map 值时,Map 中的 Java 嵌套列表返回错误

java - GWT序列化: polymorphism with generics

java - jsp中如何获取下拉列表中选中的文本

java - JHipster Eclipse 插件错误

java - 什么是 List 与 ArrayList?

java - 如何在 gradle 上强制使用 gradlew?

c++ - clang : error: linker command failed with exit code 1 (use -v to see invocation) in C++ code

vba - 在 VBA 中将参数传递给构造函数

python - 可以从嵌套类定义实现继承吗?

c# - 泛型的观察者模式