Java获取泛型参数类

262
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
//此时A的类型为一个泛型
class A<T> {
    //A的构造器
    public A() {
        //谁调用就是谁的Class类型
        Class clazz = this.getClass();
        Type type = clazz.getGenericSuperClass();
        ParameterizedType ptype = (ParameterizedType) type;
        //多个参数类型,本例中只有一个
        Type[] types = ptype.getActualTypeArguments();
        Class c = (Class) types[0];
    }
}
//子类B为父类传递参数的类型是String
Class B extends A<String> {}
//子类C为父类传递参数的类型是Integer
Class C extends A<Integer> {}

//测试
public class Test {
    public void main(String args[]) {
        new B();  //构造时调用了父类A的构造方法打印出java.lang.String
        new C();  //构造时调用了父类A的构造方法打印出java.lang.Integer
    }
}