我如何学习泛型类的实际类型参数? [英] How can I learn actual type argument of an generic class?
问题描述
我有一个参数化类:
I have a parameterized class :
class ParameterizedClass<T extends AbstractSomething> {
}
通话:
new ParameterizedClass<Something>();
那么我怎样才能得到实际的类型 T
使用Java泛型?
So how can I get actual type Something of T
by using Java Generics?
推荐答案
可以这样做,但 type erasure 可以使其变得非常困难。正如其他答案所讨论的那样,您必须创建 ParameterizedClass
的子类,或将类型为 T
的字段添加到 ParameterizedClass
,你需要做的反射代码是复杂的。
It can be done, but type erasure can make it very hard. As the other answers discuss, you either have to make a subclass of ParameterizedClass
or add a field of type T
to ParameterizedClass
, and the reflection code you need to do it is convoluted.
我在这些情况下推荐的是解决这个问题:
What I recommend in these circumstances, is to work around the issue like this:
class ParameterizedClass<T> {
private Class<T> type;
/** Factory method */
public static <T> ParameterizedClass<T> of(Class<T> type) {
return new ParameterizedClass<T>(type);
}
/** Private constructor; use the factory method instead */
private ParameterizedClass(Class<T> type) {
this.type = type;
}
// Do something useful with type
}
$ b $由于Java对静态方法的类型推断,您可以构造您的类,而不需要额外的样板:
Due to Java's type inference for static methods, you can construct your class without too much extra boilerplate:
ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class);
这样,您的 ParameterizedClass
是完全通用的和类型安全的,并且您仍然可以访问类对象。
That way, your ParameterizedClass
is fully generic and type-safe, and you still have access to the class object.
编辑:解决了注释
这篇关于我如何学习泛型类的实际类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!