I have generic type with Class<T>
object provided in constructor. I want to create two-dimensional array T[][]
in this constructor, is this however possible?
Same as How to create a generic array in Java? but extended to 2D:
import java.lang.reflect.Array;
public class Example <T> {
private final Class<? extends T> cls;
public Example (Class<? extends T> cls) {
this.cls = cls;
}
public void arrayExample () {
// a [10][20] array
@SuppressWarnings("unchecked")
T[][] array = (T[][])Array.newInstance(cls, 10, 20);
System.out.println(array.length + " " + array[0].length + " " + array.getClass());
}
public static final void main (String[] args) {
new Example<Integer>(Integer.class).arrayExample();
}
}
Note after reading JAB's comment above: To extend to more dimensions, just add []'s and dimension parameters to newInstance() (cls is a Class, d1 through d5 are integers):
T[] array = (T[])Array.newInstance(cls, d1);
T[][] array = (T[][])Array.newInstance(cls, d1, d2);
T[][][] array = (T[][][])Array.newInstance(cls, d1, d2, d3);
T[][][][] array = (T[][][][])Array.newInstance(cls, d1, d2, d3, d4);
T[][][][][] array = (T[][][][][])Array.newInstance(cls, d1, d2, d3, d4, d5);
See Array.newInstance()
for details.
You have to use reflection, but it's possible: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html#newInstance%28java.lang.Class,%20int...%29
Creates a new array with the specified component type and dimensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With