JAVA中通过反射获得泛型的实际参数

前言

原创文章欢迎转载,请保留出处。
若有任何疑问建议,欢迎回复。
邮箱:Maxwell_nc@163.com

由于不能通过一个变量来获取他的泛型实际参数,我们参考hibernate的源码,通过反射来获得泛型的实际参数。


通过反射获得泛型的实际参数

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class GenericTest {

    public static void main(String[] args)throws Exception {    
        //首先获得传入泛型参数的方法
        Method applyMethod = GenericTest.class.getMethod("applyArrayList", ArrayList.class);
        //使用getGenericParameterTypes方法,这个方法只有在JDK 1.5以上才能用
        Type[] types = applyMethod.getGenericParameterTypes();
        //把获得Type数组转成ParameterizedType
        ParameterizedType pType = (ParameterizedType)types[0];
        //ParameterizedType中的两个方法分别获取原始类型和泛型实际参数
        System.out.println(pType.getRawType());
        System.out.println(pType.getActualTypeArguments()[0]);
    }

    public static void applyArrayList(ArrayList<String> arr){}
}

运行结果

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值