ckw
ckw

Reputation: 1

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!

Upvotes: 0

Views: 289

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234847

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.

Upvotes: 7

karmakaze
karmakaze

Reputation: 36164

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.

Upvotes: 0

Related Questions