码迷,mamicode.com
首页 > 其他好文 > 详细

获取泛型类型工具类

时间:2014-11-18 22:59:35      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   java   div   on   

Java泛型在编译阶段会进行泛型擦除,所以能够在运行期获得的泛型是在编译阶段已经确定(继承的泛型类)了的。

 1 public class GenricUtils {
 2     /**
 3      * 获得泛型类型
 4      * @param clz
 5      * @return
 6      */
 7     public static <T> Class<T> getGenricClassType(Class clz){
 8         Type type = clz.getGenericSuperclass();
 9         if(type instanceof ParameterizedType){
10             ParameterizedType pt = (ParameterizedType) type;
11             Type[] types = pt.getActualTypeArguments();
12             if(types.length > 0 && types[0] instanceof Class){
13                 return (Class) types[0];
14             }
15         }
16         return (Class) Object.class;
17     }
18 }

比如:

1 class TestA<T>{
2     private Class<T> clz = GenricUtils.getGenricClassType(TestA.class);
3     public  void get(String id){
4         session.get(clz,id);
5     }
6 }
7 class TestB extends TestA<String>{
8 }

在执行:

System.out.println(getGenricClassType(TestA.class));
System.out.println(getGenricClassType(TestB.class));

输出的结果分别为:

class java.lang.Object
class java.lang.String

 

获取泛型类型工具类

标签:style   blog   io   color   ar   sp   java   div   on   

原文地址:http://www.cnblogs.com/libaoting/p/4106417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!