Java获取父类的泛型信息

对于泛型类型的属性和方法可以通过Filed和Method在运行时获取泛型信息,但是如何在运行时获取泛型类的泛型信息呢?

我们知道java的泛型是伪泛型,只是在编译的时候进行类型检查,编译后,所有的泛型信息都会被擦除,因此在运行时无法使用反射获取范型的类型。比如对于泛型类List<String> ,在编译的时候会检测所有加入到list里面的是否是String类型,编译后的class文件中是不会有范型信息的。

那么该如何获取泛型类的泛型信息呢,可以通过子类继承泛型类的方法来实现。

public class GenericTest {
    
    

    public static abstract class ParentClass<T> {
    
    
        T name;

        public T getName() {
    
    
            return name;
        }

        public void setName(T name) {
    
    
            this.name = name;
        }
    }

    public static class Child extends ParentClass<String> {
    
    

    }

    /**
     * 通过父类去获取泛型类型
     */
    public static void getActualType() {
    
    
        Child child = new Child();
        Type type = child.getClass().getGenericSuperclass();
        if(type instanceof ParameterizedType) {
    
    
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Type actualtype = parameterizedType.getActualTypeArguments()[0];
            System.out.println(actualtype);//class java.lang.String

        }
    }


    public static void main(String[] args) {
    
    
        getActualType();
    }

}

java在编译的时候会检测父类的范型信息,因为子类声明了范型的类型,所以子类的class文件中记录该子类声明的范型类型,所以只有在这种情况下才能在运行时通过反射API获取到该范型的类型。

猜你喜欢

转载自blog.csdn.net/yzpbright/article/details/107768967