leisure

JAVA - exceed,helloworld
随笔 - 50, 文章 - 0, 评论 - 11, 引用 - 0
数据加载中……

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

获取泛型参数的类型
        
Class<TentityClass = (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);

posted on 2011-12-26 14:37 leisure 阅读(17847) 评论(4)  编辑  收藏

评论

# re: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType[未登录]  回复  更多评论   

BasicService.class,不就是我需要的类型吗?你Y的相当于脱了裤子放屁一样,传入某类型对象又获取某类型对象,有意义吗?
2013-02-05 15:47 | 小熊

# re: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType[未登录]  回复  更多评论   

@小熊

楼上的,没看懂!楼主是拿泛型的Class类型。
没文化,等你到了这个层次,你就会理解。好好看多点架构方面的吧。

2013-03-07 11:57 | peter

# re: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType  回复  更多评论   

很对!
2013-05-21 18:43 | yenshi

# re: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType  回复  更多评论   

还是不成功咋办
2013-09-25 12:42 | txy779

只有注册用户登录后才能发表评论。


网站导航: