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

不知道大家有没有尝试过怎样获得一个泛型的实际类型参数?其实这个功能在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() {
    }

}

输出:
输出结果

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

posted @ 2015-05-02 16:36  江南一点雨  阅读(995)  评论(0编辑  收藏  举报