Getting the Length and Dimensions of an Array Object - Java Reflection

Java examples for Reflection:Array

Description

Getting the Length and Dimensions of an Array Object

Demo Code


import java.lang.reflect.Array;

public class Main {
  public static void main(String[] args) {
    Object o = new int[1][2][3];

    // Get length
    int len = Array.getLength(o); // 1

    // Get dimension
    int dim = getDim(o); // 3
  }//  w  ww .j a v  a2 s .c o m
  public static int getDim(Object array) {
    int dim = 0;
    Class cls = array.getClass();
    while (cls.isArray()) {
      dim++;
      cls = cls.getComponentType();
    }
    return dim;
  }
}

Related Tutorials