gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:12 25 4
gpt4 key购买 nike

我需要将泛型类型的类传递给类的构造函数。类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com