Multidimensional reflection of java length array

How to find the length of a multidimensional array with reflection in java?

+6
java arrays reflection
source share
5 answers

Java arrays are one instance long, and not all arrays in the same dimension must have equal lengths. However, you can get the length of the instances in.

Sizes can be counted by the number '[' in their name, this is faster than descending the type hierarchy. The following code:

int[][][] ary = {{{0},{1}}}; Class cls = ary.getClass(); boolean isAry = cls.isArray(); String clsName = cls.getName(); System.out.println("is array=" + isAry); System.out.println("name=" + clsName); int nrDims = 1 + clsName.lastIndexOf('['); System.out.println("nrDims=" + nrDims); Object orly = ary; for (int n = 0; n < nrDims; n++) { int len = Array.getLength(orly); System.out.println("dim[" + n + "]=" + len); if (0 < len) { orly = Array.get(orly, 0); } } 

gives the following result:

 is array=true name=[[[I nrDims=3 dim[0]=1 dim[1]=2 dim[2]=1 
+9
source share

There is no such thing as β€œlength” for a multidimensional array; it may not be rectangular. I assume that you are talking about the number of dimensions. You need to go down iteratively and count.

 public int getDimensionCount(Object array) { int count = 0; Class arrayClass = array.getClass(); while ( arrayClass.isArray() ) { count++; arrayClass = arrayClass.getComponentType(); } return count; } 
+12
source share
 Class clazz = Class.forName("ReflectionTest"); Method m = clazz.getDeclaredMethod("getArray"); Object o1 = m.invoke(o, arg); int array[][] = (int[][])o1; System.out.println("Array length: " + array.length); System.out.println("Array length: " + array[0].length); 
0
source share

Use java.lang.reflect.Array.getLength(obj) .

0
source share

If I like you, I try to get the number of dimensions and their size:

 private static int[] getDimentionsOf(final Object expectedArray) { if (!expectedArray.getClass().isArray()) { return new int[0]; } final int dimensionSize = Array.getLength(expectedArray); final int[] innerDimensions = (expectedArray.getClass().getComponentType().isArray()) ? getDimentionsOf(Array.get(expectedArray, 0)) : new int[0]; final int lenghtPlusOne = innerDimensions.length + 1; final int[] newDimensions = new int[lenghtPlusOne]; System.arraycopy(innerDimensions, 0, newDimensions, 1, innerDimensions.length); newDimensions[0] = dimensionSize; return newDimensions; } 
0
source share

All Articles