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

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

public class GenericsTest {@Test(){try {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();}}(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;}(Attribute attribute) {this.attribute = attribute;}public Detail getDetail() {return detail;}(Detail detail) {this.detail = detail;}() {return id;}(int id) {this.id = id;}public String getName() {return name;}(String name) {this.name = name;}() {return price;}(int price) {this.price = price;}public String getAuthor() {return author;}(String author) {this.author = author;}public Book(String name, String author) {this.name = name;this.author = author;}public Book() {}}

输出:

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

孤独是为了孤独背后的解脱,孤独的过程,就是一个寻找真爱的过程。

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

相关文章:

你感兴趣的文章:

标签云: