8

How do I find the length of a multi-dimensional array with reflection on java?

5 Answers 5

14

There is no such thing as "length" for multi-dimensional array; it may not be rectangular. I'm guessing you're talking about the number of dimensions. You need to descend into it iteratively and count.

public int getDimensionCount(Object array) {
  int count = 0;
  Class arrayClass = array.getClass();
  while ( arrayClass.isArray() ) {
    count++;
    arrayClass = arrayClass.getComponentType();
  }
  return count;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You first have to check whether Object array is an array.
You don't, because the while loop checks for you--if it is an array, the method will just return 0.
10

Java arrays have lengths per instance, not all arrays in the same dimension have to have equals lengths. That said, you can get the lengths of instances in the.

Dimensions can be counted by the number of '[' in their name, this is quicker 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 output:

is array=true
name=[[[I
nrDims=3
dim[0]=1
dim[1]=2
dim[2]=1

Comments

0
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);

1 Comment

I see what you are saying. You could create a method that can be invoked from that class that will return the number of dimensions. If you cannot modify that class, I'm not sure.
0

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

1 Comment

Multidimensional arrays are arrays of arrays. getLength will return indeed the size of one array, but now you know the size of the containing array. Using a loop from 0 to found length – 1, you can apply getLength on each element of that first array and find out the other sizes.
-1

If you like me were trying to get the number of dimensions and the size of them then:

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;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.