1
回答

public class Father <T>{ protected Class<T> clazz; public Father() { clazz = GenericsUtils.getSuperClassGenricType(this.getClass(), 0); } }
@SuppressWarnings("unchecked") public static Class getSuperClassGenricType(Class clazz, int index){ System.out.println(Father.class.getGenericSuperclass()); Type genType = clazz.getGenericSuperclass();// 得到泛型父类 // 如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class if (!(genType instanceof ParameterizedType)){ return Object.class; } // 返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型 Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0){ throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数")); } if (!(params[index] instanceof Class)){ return Object.class; } return (Class) params[index]; }
场景类是
public class Test extends Father<Dog>{ public static void main(String[] args) { Test t = new Test(); } }我在Father的构造方法里面
先后这样调用
clazz = GenericsUtils.getSuperClassGenricType(this.getClass(), 0);
clazz = GenericsUtils.getSuperClassGenricType(Father.class, 0);
结果发现前者才正确。
所以想问下这里this.getClass和Father.Class有什么不同呢?