java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

获取泛型参数的类型

Class < T entityClass  =  (Class < T > )((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[ 0 ];

出现:
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

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

 Class<TentityClass = GenericsUtils.getSuperClassGenricType(BasicService.class0);


相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页