Given some object o
, I need to find its dimensionality (eg: for int[x][y][z]
the dimensionality is 3
), I figured that any appropriate method would be in the class of the object.
int dimensionality = o.getClass().getName().indexOf('L');
works, but its source refers to a native method, so I'm left getting the answer from a string, rather than directly.
If anyone knows a better way of doing this it would be appreciated (although more for the sake of curiosity than necessity).
Here's a recursive solution using Class.isArray
:
static int getDimensionality(final Class<?> type) {
if (type.isArray()) {
return 1 + getDimensionality(type.getComponentType());
}
return 0;
}
public static void main (String[] args) {
System.out.println(getDimensionality(int.class)); // 0
System.out.println(getDimensionality(int[].class)); // 1
System.out.println(getDimensionality(int[][].class)); // 2
System.out.println(getDimensionality(int[][][].class)); // 3
}
Although as PM 77-1 points out, this is not truly a measure of dimensionality but of the depth of a jagged array in terms of its static type. There are no true multidimensional arrays in Java, just arrays of arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With