zoukankan      html  css  js  c++  java
  • 通过反射获得泛型的实际类型参数

    不知道大家有没有尝试过怎样获得一个泛型的实际类型参数?其实这个功能在hibernate中有广泛的应用,那么具体的操作是怎样的呢?
    首先,要想直接通过一个变量拿到泛型类型中的实际参数显然是不可能的,参考hibernate源码,只要把这个变量当作一个方法的参数,再通过反射就可以拿到该泛型类型的实际参数。

    public class GenericsTest {
    
        @Test
        public void test7(){
           try {
            //List<Book> list = new ArrayList<Book>();
               //加入我现在想拿到上面这个list泛型中的实际类型参数,那么先写一个方法,以之为参数
                //下面利用反射拿到list的实际类型参数
                Method m = GenericsTest.class.getMethod("test8", List.class);
                //获得泛型类型参数
                Type[] types = m.getGenericParameterTypes();
                //因为只有一个参数,所以我们拿第一个就可以了
                ParameterizedType pt = (ParameterizedType) types[0];
                //获得原始类型
                System.out.println(pt.getRawType());
                //获得实际参数类型,实际参数类型也是一个数组,比如Map<String,String>
                //这里只有一个参数,我们就不遍历了
                System.out.println(pt.getActualTypeArguments()[0]);
        } catch (NoSuchMethodException | SecurityException e) {
            e.printStackTrace();
        }
        }
        public void test8(List<Book> list){
    
        }
    }
    

    Book.java

    package lenve.test;
    
    public class Book {
    
        private int id;
        private String name;
        private int price;
        private String author;
        private Detail detail;
        private Attribute attribute;
    
        public Attribute getAttribute() {
            return attribute;
        }
        public void setAttribute(Attribute attribute) {
            this.attribute = attribute;
        }
        public Detail getDetail() {
            return detail;
        }
        public void setDetail(Detail detail) {
            this.detail = detail;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getPrice() {
            return price;
        }
        public void setPrice(int price) {
            this.price = price;
        }
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public Book(String name, String author) {
            this.name = name;
            this.author = author;
        }
        public Book() {
        }
    
    }

    输出:
    输出结果

    怎么样?拿到实际类型参数了吧!

  • 相关阅读:
    LeetCode Array Easy 1. Two Sum
    关于VS2015 发布.net mvc 网站失败的问题
    2016计蒜之道复赛 百度地图的实时路况 floyd+cdq分治
    2016计蒜之道复赛 菜鸟物流的运输网络 网络流EK
    HDU5715 XOR 游戏 二分+字典树+dp
    HDU5697 刷题计划 dp+最小乘积生成树
    codeforces 687D Dividing Kingdom II 带权并查集(dsu)
    codeforces 687C
    codeforces 687B
    HDU 5693 D Game 区间dp
  • 原文地址:https://www.cnblogs.com/lenve/p/4517996.html
Copyright © 2011-2022 走看看