在java 中 上网查了一下Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; 但是 这个无法得到自己本身的泛型。而调用getGenericSuperclass()方法得到的是父类的泛型。
话不多说 直接上代码
父类:
import
java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* 父类
* @author linfanhe
*
* @param <T>
*/
public class Father<T> {
Class<T> clazz;
//构造函数
public Father(){
Type type = this.getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
clazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
} else {
throw new RuntimeException(this.getClass().getName() + "没有指定PO的类型");
}
// clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
}
子类:
public
class Child extends Father<Integer> {
public Child()
{
System.out.println(clazz);
}
public static void main(String[] args){
Child c = new Child();
}
}