vendredi 27 février 2015

Instantiate and store generic arrays

Good day everyone. My problem has been discussed many times on SO, but i cant find answer anyway. So, I need to store array of generics in my generic class instance:



public class GenericArrayStorage<Item> implements Iterable<Item> {

private Item[] storage;
....
}


Obviously, I cant work with storage like with array of concrete objects (my IDE shows error Generic array creation on new Item[]). After some research i wrote this code:



@SuppressWarnings("unchecked")
public GenericArrayStorage() {
ParameterizedType genericSuperclass =
(ParameterizedType) getClass().getGenericSuperclass(); //error
Class clazz = (Class) genericSuperclass.getActualTypeArguments()[0];
storage = (Item[]) Array.newInstance(clazz, 10);
}


But this leads to following error: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType


I said OK and wrote this:



@SuppressWarnings("unchecked")
public GenericArrayStorage() {
ParameterizedType pt =
(ParameterizedType) getClass().getGenericInterfaces()[0];
Class clazz = (Class) pt.getActualTypeArguments()[0]; //error
storage = (Item[]) Array.newInstance(clazz, 10);
}


This one causes another exception: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class. Sad but true.


Then I added .getClass() to pt.getActualTypeArguments()[0] and my constructor now don't throw any errors. However, when i try to work with this array after new GenericArrayStorage<Integer>(), it throws following: java.lang.ArrayStoreException: java.lang.Integer. This line causes exception: storage[0] = new Integer(1);


So, how could i work with generic array?






Aucun commentaire:

Enregistrer un commentaire