1. Exception in thread "main" java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class 2. at Test.<init>(Test.java:14) 3. at Test.main(Test.java:20) 1. import java.lang.reflect.ParameterizedType; 2. import java.lang.reflect.Type; 3. 4. public class GenericsUtils { 5. /** 6. * 通过反射,获得定义Class时声明的父类的范型参数的类型. 7. * 如public BookManager extends GenricManager<Book> 8. * 9. * @param clazz The class to introspect 10. * @return the first generic declaration, or <code>Object.class</code> if cannot be determined 11. */ 12. public static Class getSuperClassGenricType(Class clazz) { 13. return getSuperClassGenricType(clazz, 0); 14. } 15. 16. /** 17. * 通过反射,获得定义Class时声明的父类的范型参数的类型. 18. * 如public BookManager extends GenricManager<Book> 19. * 20. * @param clazz clazz The class to introspect 21. * @param index the Index of the generic ddeclaration,start from 0. 22. */ 23. public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException { 24. 25. Type genType = clazz.getGenericSuperclass(); 26. 27. if (!(genType instanceof ParameterizedType)) { 28. return Object.class; 29. } 30. 31. Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); 32. 33. if (index >= params.length || index < 0) { 34. return Object.class; 35. } 36. if (!(params[index] instanceof Class)) { 37. return Object.class; 38. } 39. return (Class) params[index]; 40. } 41. }