JavaSE 反射 Part4

来源:互联网 发布:怎么理解面向对象编程 编辑:程序博客网 时间:2024/06/05 08:43

原作者:尚硅谷-佟刚


package com.atweihai.reflection;public class PersonDao extends Dao<Person> {}
package com.atweihai.reflection;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;public class Dao<T> {    private Class<T> clazz;    public Dao() {        //获取Dao子类的带泛型参数的父类  com.atweihai.reflection.Dao<com.atweihai.reflection.Person>        Type type=this.getClass().getGenericSuperclass();        //获取具体的泛型参数        if(type instanceof ParameterizedType){            //强转成带参数的父类类型   com.atweihai.reflection.Dao<com.atweihai.reflection.Person>            ParameterizedType parameterizedType=(ParameterizedType) type;            //获取实际的泛型参数 对应的Class 数组    [class com.atweihai.reflection.Person]            Type[] args=parameterizedType.getActualTypeArguments();            //得到Class<T> 类型的 class            if(args!=null&&args.length>0){                Type arg=args[0];                if(arg instanceof Class){                    clazz=(Class<T>) arg;                }            }        }    }    T get(Integer id){        System.out.println(clazz);        return null;    }    void save(T entity){    }}

测试代码

@Test    public void testGenericAndReflection(){        PersonDao personDao=new PersonDao();        personDao.get(1);    }

测试结果


原创粉丝点击