1、獲取父類泛型類的泛型
public abstract class AbstractDao<T> { public Class<T> getActualType() { ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass(); return (Class<T>) parameterizedType.getActualTypeArguments()[0]; } } public class UserDao extends AbstractDao<String> { public static void main(String[] args) { UserDao userDao = new UserDao(); Class<String> actualType = userDao.getActualType(); System.out.println(actualType.getName()); } }
2、獲取成員變量的泛型
public class User { private List<String> list; public static void main(String[] args) { try { Field field = User.class.getDeclaredField("list"); Type genericType = field.getGenericType(); if (genericType != null && genericType instanceof ParameterizedType) { Type actualType = ((ParameterizedType) genericType).getActualTypeArguments()[0]; System.out.println(actualType.getTypeName()); } } catch (Exception e) { } } }
3、獲取局部變量的泛型,注意:泛型必須以匿名內部類的方式
public abstract class AbstractDao<T> { public Class<T> getActualType() { ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass(); return (Class<T>) parameterizedType.getActualTypeArguments()[0]; } public static void main(String[] args) { AbstractDao<String> dao = new AbstractDao<String>() { }; System.out.println(dao.getActualType().getTypeName()); } }
4、通過接口/父類的匿名內部類作為參數傳遞到方法
在方法中可以獲得匿名內部類繼承的父類或實現的接口的泛型的真實類型
AbstractDao如參考例子一,是一個帶泛型的抽象類
打印如下:
總結一下
如果是繼承基類而來的泛型,就用 getGenericSuperclass() , 轉型為 ParameterizedType 來獲得實際類型
如果是實現接口而來的泛型,就用 getGenericInterfaces() , 針對其中的元素轉型為 ParameterizedType 來獲得實際類型
我們所說的 Java 泛型在字節碼中會被擦除,並不總是擦除為 Object 類型,而是擦除到上限類型
能否獲得想要的類型可以在 IDE 中,或用 javap -v <your_class> 來查看泛型簽名來找到線索
轉載:https://blog.csdn.net/qq_30038111/article/details/100611523
https://blog.csdn.net/hj7jay/article/details/54889717