Thanks to the comments, I was able to put together a solution.
As we saw, A<String>[][] array = new A<String>[2][3]; does not work.
Here's how to build an array of 2x3 A<String> objects that works:
// get the class of the basic object Class c = new A<String>("t").getClass(); // get the class of the inner array A<String>[] a0 = (A<String>[]) java.lang.reflect.Array.newInstance(c, 0); // construct the outer array A<String>[][] array = (A<String>[][]) java.lang.reflect.Array.newInstance(a0.getClass(), 2); // fill it with instances of the inner array for (int i = 0; i < 2; ++ i) { array[i] = (A<String>[]) java.lang.reflect.Array.newInstance(c, 3); }
Cleaner version (thanks, @Balla R):
@SuppressWarnings("unchecked") A<String>[][] array = (A<String>[][]) java.lang.reflect.Array.newInstance(A.class,2,3);
dsg
source share