package com.wzs; import java.lang.reflect.ParameterizedType; public class T1<T> { private Class classt; public T1() { ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass(); this.classt = (Class) type.getActualTypeArguments()[0]; System.out.println(this.classt); } }
package com.wzs; public class T2<T> extends T1<T> { public static void main(String[] args) { T2 t = new T2(); } }
Exception in thread "main" java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class at com.wzs.T1.<init>(T1.java:10) at com.wzs.T2.<init>(T2.java:3) at com.wzs.T2.main(T2.java:5)
T1为父类,T2为子类,T2继承T1后报错类型转换异常,在网上查找N久资料才找到解决办法,出现问题原因还不是太明白(惭愧),不过知道怎么解决了。
下边贴出来修改后正常运行的代码,希望对大家有所帮助。
package com.wzs; import java.lang.reflect.ParameterizedType; public class T1<T> { private Class classt; public T1() { ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass(); this.classt = (Class) type.getActualTypeArguments()[0]; System.out.println(this.classt); } }
package com.wzs; public class T2 extends T1<Integer> { public static void main(String[] args) { T2 t = new T2(); } }
class java.lang.Integer
sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class异常解决方法
原文:http://blog.csdn.net/adam_wzs/article/details/25915203