I want to create an array of classes and I have these:
1)works fine
Class<MyClass>[] array = (Class<MyClass>[]) new Class<?>[list.size()];
2)java.lang.ClassCastException
Class<MyClass>[] array = (Class<MyClass>[]) Array.newInstance(MyClass.class, list.size());
3)we have a generic method , works fine
public static <T> List<T> method(T arg , T[] array){
array = (T[]) Array.newInstance(arg.getClass(), 1);
ArrayList<T> list = new ArrayList<T>(Arrays.asList(array));
array[0] = arg;
return new ArrayList<T>(Arrays.asList(array));
}
Please explain why we get the exception in 2 ? As I understand we are doing the same thing in 3 , so what's the difference ?
UPDATE
I guess my confusion is because we have:
Type mismatch: cannot convert from List< Class < MyClass > > to List< MyClass >
List<MyClass> list = Utils.addToList(MyClass.class, null);
Works
List<Class<MyClass>> list = Utils.method(MyClass.class, null);
I think I'm missing something , but I'm not sure what...
So it's finally clear what exacly I had in mind:
List<Class<MyClass>> list = Utils.method(MyClass.class, null);
Class<MyClass>[] array2 = (Class<MyClass>[]) Array.newInstance(MyClass.class.getClass(), list.size());
List<Class<MyClass>> list2 = Utils.method(MyClass.class, list.toArray(array2));
Both snippets 2 and 3 are creating a MyClass[]
, not a Class<MyClass>[]
.
The element type is determined by the first argument to Array.newInstance
. If you want an array where each element is a Class
reference, you need to pass in Class.class
.
Note that generics and arrays don't play terribly nicely together - which is why you get a warning even for your "works fine" code.
See more on this question at Stackoverflow