JavaSE 反射 Part4

Java泛型与反射实践
本文介绍了一个使用Java泛型和反射技术的具体案例,通过定义一个泛型DAO类来实现不同类型对象的数据操作,并利用反射机制在运行时动态获取泛型参数的实际类型。

原作者:尚硅谷-佟刚


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);
    }

测试结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值