我经常会想获取参数的实际类型,在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"); } }