问题描述
父类Father如下
public class Father {
private int id;
}
子类Child
public class Child extends Father{
private String name;
}
public class Test<T extends Father>{
private void test(){
T temp = (T)new Father();
}
}
public class ChildTest extends Test<Child>{
//sth
}
如果直接在ChildTest调用test()方法,得到的temp对象是没有name属性的
解决办法
在Test方法中增加
private Class<T> clz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
然后修改test()方法如下,即可
private void test(){
T temp = clz.newInstance();
//do sth
}