I am making a class that contains an instance variable of type Object[]
that is named array
. This class includes a method that returns a T[]
, where T
is a generic. The method should copy the contents of array
on to the array to be returned. The relevant code looks like this:
@SuppressWarnings("unchecked")
T[] arr = (T[])Array.newInstance(a.getClass(), array.length);
for (int i = 0; i < array.length; i++) {
@SuppressWarnings("unchecked")
T temp = (T)array[i];
arr[i] = temp;
}
return arr;
In the above snippet, a
is yet another array that was passed as a parameter.
The issue is, when I call the method, it throws an ArrayStoreException
. I'm not sure why it is doing that because I am casting the initial value to type T
before storing it in the array which is of type T[]
, so the types match. Why is is still throwing the exception?
With that code you create an
T[][]
becausea.getClass()
isClass<T[]>
.What you want is
a.getClass().getComponentType()
, thats the actualClass<T>
So:
Or you can use the jre method