java 获取泛型类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5433170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get class of generic
提问by kospiotr
My class starts with
我的课开始于
public abstract class LastActionHero<H extends Hero>(){
Now somewhere in the code I want to write H.class
but that isn't possible (like String.class
or Integer.class
is).
现在在我想写的代码中的某个地方,H.class
但这是不可能的(就像String.class
或是Integer.class
)。
Can you tell me how I can get the Class
of the generic?
你能告诉我如何获得Class
泛型的吗?
采纳答案by Peter Lawrey
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: It not impossible to get this dynamically, but it depends on how it is used. e.g
顺便说一句:动态获取它并非不可能,但这取决于它的使用方式。例如
public class Arnie extends LastActionHero<MuscleHero> { }
It is possible to determine that Arnie.class has a super class with a Generic parameter of MuscleHero.
可以确定 Arnie.class 有一个超类,其 Generic 参数为 MuscleHero。
public class Arnie<H extend Hero> extends LastActionHero<H> { }
The generic parameter of the super class will be just H
in this case.
超类的泛型参数就是H
这种情况。
回答by kospiotr
We do it in the following way:
我们通过以下方式做到这一点:
private Class<T> persistentClass;
public Class<T> getPersistentClass() {
if (persistentClass == null) {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
return persistentClass;
}
回答by Buhake Sindi
One way is to keep reference to your parameterized type like having an attribute of
一种方法是保留对参数化类型的引用,例如具有
private Class<H> clazz;
And create a setter or a constructor that takes in a Class<H>
.
并创建一个接受Class<H>
.
Parameterized Types are erased at runtime, hence why you can't do what you ask.
参数化类型在运行时被删除,因此为什么你不能按你的要求做。
回答by Peter Tseng
You can do it without passing in the class:
您可以在不传入类的情况下执行此操作:
public abstract class LastActionHero<H extends Hero>() {
Class<H> clazz = (Class<H>) DAOUtil.getTypeArguments(LastActionHero.class, this.getClass()).get(0);
}
You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java
您需要此文件中的两个函数:http: //code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil。爪哇
For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860
更多解释:http: //www.artima.com/weblogs/viewpost.jsp?thread= 208860
回答by Puppy
You can't- the type is erased at run-time and exists only at compile-time.
你不能 - 类型在运行时被擦除并且只在编译时存在。