我經常會想獲取參數的實際類型,在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"); } }