0

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!

ckw
  • 1

2 Answers2

7

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.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

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.

karmakaze
  • 34,689
  • 1
  • 30
  • 32