获取类的泛型 [英] Get class of generic
问题描述
我的课程以
public abstract class LastActionHero<H extends Hero>(){
现在代码中我想写 H.class
可能(像 String.class
或 Integer.class
是)。
Now somewhere in the code I want to write H.class
but that isn't possible (like String.class
or Integer.class
is).
你能告诉我如何获得通用的 Class
吗?
Can you tell me how I can get the Class
of the generic?
推荐答案
您可以动态提供类型,但编译器不会自动执行此操作。
You can provide the type dynamically, however the compiler doesn't do this for you automagically.
public abstract class LastActionHero<H extends Hero>(){
protected final Class<H> hClass;
protected LastActionHero(Class<H> hClass) {
this.hClass = hClass;
}
// use hClass how you like.
}
BTW:这不是不可能动态获得,用来。例如
BTW: It not impossible to get this dynamically, but it depends on how it is used. e.g
public class Arnie extends LastActionHero<MuscleHero> { }
可以确定Arnie.class有一个带有Generic参数MuscleHero
It is possible to determine that Arnie.class has a super class with a Generic parameter of MuscleHero.
public class Arnie<H extend Hero> extends LastActionHero<H> { }
超类的泛型参数将只是 H
在这种情况下。
The generic parameter of the super class will be just H
in this case.
这篇关于获取类的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!