Java 泛型类 - 确定类型 [英] Java Generic Class - Determine Type
问题描述
如果我要创建一个泛型的java类,例如:
If I am creating a java class to be generic, such as:
public class Foo<T>
如何在内部确定该类的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
}
我已经研究了 Java API 并使用了 Reflection 的东西、instanceof、getClass、.class 等,但我似乎无法对它们做出正面或反面.我觉得我很接近了,只需要结合一些电话,但要保持简短.
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.
更具体地说,我试图确定该类是否使用 3 种可能类型之一进行了实例化.
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/accessing-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屋!