Get the Length and Dimensions of an Array Object in Java

Description

The following code shows how to get the Length and Dimensions of an Array Object.

Example


/*from   w  w  w.  j a  va 2s  .c o  m*/
import java.lang.reflect.Array;

public class Main {
  public static void main(String[] argv) throws Exception {
    Object o = new int[1][2][3];
    int len = Array.getLength(o); // 1
    System.out.println(len);
    int dim = getDim(o); // 3
    System.out.println(dim);
  }

  public static int getDim(Object array) {
    int dim = 0;
    Class cls = array.getClass();
    while (cls.isArray()) {
      dim++;
      cls = cls.getComponentType();
    }
    return dim;
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy