Java通用类 - 确定类型 [英] Java Generic Class - Determine Type
问题描述
如果我将java类创建为通用类,如:
public class Foo< T>
在内部如何确定这个班级,最后是什么'T'?
public ???? Bar()
{
//如果其类型1
//执行此操作
//如果其类型2
//执行此操作
//如果它的类型3
//做这个
//如果它的类型4
//做这个
}
我使用了Java API,并且使用了Reflection的东西,instanceof,getClass,.class等,但我似乎无法做出正面或反面的评论他们。我觉得我很接近,只需要结合一些电话,但不断缩短。
更具体地说,我试图确定类被实例化为3种可能的类型之一。
我已经使用了类似的解决方案,项目,并发现它非常有用。
http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/ <
公共类returnedclass() ){
ParameterizedType parameterizedType =(ParameterizedType)getClass()
.getGenericSuperclass();
return(Class)parameterizedType.getActualTypeArguments()[0];
}
If I am creating a java class to be generic, such as:
public class Foo<T>
How can one determine internally to that class, what 'T' ended up being?
public ???? Bar()
{
//if its type 1
// do this
//if its type 2
// do this
//if its type 3
// do this
//if its type 4
// do this
}
I've poked around the Java API and played with the Reflection stuff, instanceof, getClass, .class, etc, but I can't seem to make heads or tails of them. I feel like I'm close and just need to combine a number of calls, but keep coming up short.
To be more specific, I am attempting to determine whether the class was instantiated with one of 3 possible types.
I've used a similar solution to what he explains here for a few projects and found it pretty useful.
http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/
The jist of it is using the following:
public Class returnedClass() {
ParameterizedType parameterizedType = (ParameterizedType)getClass()
.getGenericSuperclass();
return (Class) parameterizedType.getActualTypeArguments()[0];
}
这篇关于Java通用类 - 确定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!