Java获取泛型真实类型的方法

时间:2025-04-04 09:08:22
  • 获取泛型类的泛型

    public abstract class AbstractDao<T> {
        public Class<T> getActualType() {
            ParameterizedType parameterizedType = (ParameterizedType) ().getGenericSuperclass();
            return (Class<T>) ()[0];
        }
    }
    
    public class UserDao extends AbstractDao<String> {
        public static void main(String[] args) {
            UserDao userDao = new UserDao();
            Class<String> actualType = ();
            (());
        }
    }
    
  • 获取成员变量的泛型

    public class User {
        private List<String> list;
        public static void main(String[] args) {
            try {
                Field field = ("list");
                Type genericType = ();
                if (genericType != null && genericType instanceof ParameterizedType) {
                    Type actualType = ((ParameterizedType) genericType).getActualTypeArguments()[0];
                    (());
                }
            } catch (Exception e) {
            }
        }
    }
    
  • 获取局部变量的泛型,注意:泛型必须以匿名内部类的方式

    public abstract class AbstractDao<T> {
    
        public Class<T> getActualType() {
            ParameterizedType parameterizedType = (ParameterizedType) ().getGenericSuperclass();
            return (Class<T>) ()[0];
        }
    
        public static void main(String[] args) {
            AbstractDao<String> dao = new AbstractDao<String>() {
            };
            (().getTypeName());
        }
    }