JAVA基础_反射获取泛型参数类型

我经常会想获取参数的实际类型,在Hibernate中就利用的这一点。

domain: Person.java

public class Person {


    // 编号
    private Long id;
    
    // 姓名
    private String name;
    
    

    public Person() {
    }

    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + "]";
    }
    
    
}

使用了泛型参数的类:GenericClass.java


public class GenericClass {

    /**
     * 打印人员信息
     * @param persons
     */
    public void printPersonInfo(List<Person> persons) {
        for (Person person : persons) {
            System.out.println(person);
        }
    }
    
    /**
     * 获取人员列表
     * @return
     */
    public List<Person> getPersonList(){
        return new ArrayList<>();
    }
    

}

获取参数泛型的实际类型:GetGenericType.java

public class GetGenericType {

    public static void main(String[] args) throws Exception {
        GenericClass genericClass = new GenericClass();
        List<Person> persons = new ArrayList<>();
        persons.add(new Person(1L, "Jim"));
        genericClass.printPersonInfo(persons);
        System.out.println("Begin get GenericClass method printPersonInfo(List<Person> persons) paramter generic type");
        // 利用反射取到方法参数类型
        Method method = genericClass.getClass().getMethod("printPersonInfo", List.class);
        // 获取方法的参数列表
        Type[] paramTypes = method.getGenericParameterTypes();
        // 由于已知只有一个参数,所以这里取第一个参数类型
        ParameterizedType type = (ParameterizedType) paramTypes[0];
        // 获取参数的实际类型
        Type[] params = type.getActualTypeArguments();
        System.out.println("params[0] = " + params[0].getTypeName());
        System.out.println("End get GenericClass method printPersonInfo(List<Person> persons) paramter generic type");

    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值