Creating a shared two-dimensional array using a class object

I have a generic type with a Class<T> object provided in the constructor. I want to create a two-dimensional array T[][] in this constructor, is this possible?

+4
source share
2 answers

Same as How to create a shared array in Java? but expanded 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 the JAB comment above: To expand to a larger size, just add [] and measurement parameters in newInstance () (cls is a class, d1 to 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() more details.

+14
source

You should 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 type and size of components.

+2
source

Source: https://habr.com/ru/post/1495811/


All Articles