开发者

how to instantiate an object based on

I want to instantiate an object based on the type of the list(that is Truck) and add to the list, I try something below, but it warns me with "sun.reflect.generics.reflectiveObjects.TypeVariableImpl incompatible with java.lang.Class"

public <T extends Car> void addRow(List<T> list) {
Class<T> clazz = (Class<T>) ((ParameterizedType) list.getClass开发者_开发问答().getGenericSuperclass()).getActualTypeArguments()[0];
T newInstance = clazz.newInstance();
list.add(newInstance);
}

method call:

List<Truck> abc = new ArrayList<Truck>;
addRow(abc);

any help? Tks all in advance!


Because of type erasure, you can't do this. See, for instance, this thread or this thread. The best you can do is either a factory class or to pass the Class instance as a separate parameter:

addRow(abc, Truck.class);

More info on type erasure can be found here.


Or if you're making all the types, you could make a method similar to clone() but which makes default instances and override the method in all classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜