Multi-Dimension length array reflection java
arrays, java, reflection
Solution
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
Problem
How do I find the length of a multi-dimensional array with reflection on java?