You can't achieve such behavior with that input data. List<X>
list expected the instance of class X, but you're trying to add the object of Type Class<? extends X>
.
Let's imagine that type X is Number(for simplicity), we have Double, Integer, Character and etc, children of Number.
So, you're doing the next thing:
You want to add the object of type Class<Integer>
to list which can hold only Numbers(not a Class<Integer>
, Class<Double>
and so on). The only thing you can do, it's create the instance of Class<Integer>
, Class<Double>
this way, using reflection:
List<X> list = //some values;
Set<Class<? extends X>> set = //some values;
for (Class<? extends X> classx : set) list.add(classx.newInstance());
But that's so bad idea to use reflection in such way.
Maybe you meant something this:
List<Class<X>> list = //some values;
Set<Class<? extends X>> set = //some values;
for (Class<? extends X> classx : set) list.add(classx);
Because still the
Class<X>
is not the same as Class<? extends X>
.
But maybe you meant something like this:
List<X> list = //some values;
Set<? extends X> set = = //some values;
for (X elem : set) list.add(elem);
Last one looks nice and it should work.