Simply:
public static class MyClass<T> {
// i don't want to keep an instance of T, if it is not necessary.
// and it is not nice, not neat.
// Or, let's say, the member are in the form of :
ArrayList<T> mArrayList = new ArrayList<T>();
// the problem of getting the generic type parameter is still present.
}
@Test
public final void test() {
MyClass<Integer> myObject = new MyClass<Integer>();
getParamType( myObject );
}
private static final <T> void getParamType(final MyClass<T> _myObject) {
System.out.println(_myObject.getClass().getTypeParameters()[0]); // T
System.out.println(((T) new Object()).getClass()); // class java.lang.Object
}
如何让代码打印class java.lang.Integer
?
我知道很多 stackoverflow 线程都在询问(并回答)这个问题。然而他们却无法解决这个问题。
- 我不知道为什么有些人需要打电话
getGenericSuperclass()
- 因为这个简单的例子不涉及继承。
- 我无法将其投射到
ParameterizedType
以及。
.
System.out.println((ParameterizedType) _myObject.getClass());
// Compile Error: Cannot cast from Class<capture#11-of ? extends TreeTest2.MyClass> to ParameterizedType
System.out.println((ParameterizedType) _myObject.getClass().getGenericSuperclass());
// Runtime Exception: java.lang.ClassCastException
根据@Thomas的指南,我找到了一个解决方法获得方式class java.lang.Integer
.
首先,我们创建一个匿名的(它需要是匿名的)的子类MyClass<T>
在测试代码中。 (这很奇怪。为什么它只支持子类?)
@Test
public final void test() {
MyClass<Integer> myObject = new MyClass<Integer>() {}; // Anonymous sub-class
getParamType( myObject );
}
然后我们可以使用getGenericSuperclass()
方法得到一个Type
然后将其投射到ParameterizedType
然后使用getActualTypeArguments()
:
private static final <T> void getParamType(final MyClass<T> _myObject) {
System.out.println( ((ParameterizedType) _myObject.getClass().getGenericSuperclass()).getActualTypeArguments()[0] );
}
完美打印class java.lang.Integer
.
This is 不太好因为测试代码应该模拟实际情况,用户很可能不会继续创建无意义的子类。
这种方法基于以下想法TypeReference 类 http://gafter.blogspot.hk/2006/12/super-type-tokens.html。但我真的不知道如何使用它。我努力了class MyClass<T> extends TypeReference<T>
。但我仍然需要创建子类MyClass<T>
具有TypeReference.getType()
prints class java.lang.Integer
.
请提供帮助,并感谢您的任何意见,因为目前还没有最好的方法。
基于上述解决方法的进一步问题:为什么只有匿名子类有效?
public static class SubMyClass<T> extends MyClass<T>{}
@Test
public final void test() {
MyClass<Integer> myObject = new MyClass<Integer>() {}; // Anonymous sub-class
getParamType( myObject ); // class java.lang.Integer
MyClass<Integer> mySubObject = new SubMyClass<Integer>(); // named sub-class
getParamType( mySubObject ); // T
}
(MyClass
and getParamType()
不变。)