Get the number of dimensions for an array in Java

Description

The following code shows how to get the number of dimensions.

Example


//from  w  w  w .j  a  v  a  2  s.c o m
public class Main {
  public static void main(String args[]) {
    String[][] data = new String[3][4];
    System.out.println(getDimension(data));
  }

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

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy