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

2163 ワード

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   
 9      *   
10      * @param clazz The class to introspect   
11      * @return the first generic declaration, or Object.class 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   
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 entityClass = GenericsUtils.getSuperClassGenricType(BasicService.class, 0);