Mega Code Archive

 
Categories / Java Tutorial / Reflection
 

Getting the Length and Dimensions of an Array Object

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