6

There is a multidimensional String array being passed in as an Object.
I'm supposed to "unfold" it and process each of its primitive entries. There's no way to know the dimensions other than by looking at the Object itself.

The difficulty i'm having is in casting. I can look up the array dimension by invoking its getClass().getName() and counting the [-s there.

But then how to cast it?

String[] sa = (String[]) arr;

is giving

Exception in thread "main" java.lang.ClassCastException: [[Ljava.lang.String; cannot be cast to [Ljava.lang.String;

Can this casting be done without any use of reflection?

Note - The array can be of any dimension - not just 1 or 2.

TIA.

Naman
  • 27,789
  • 26
  • 218
  • 353
xavierz
  • 335
  • 1
  • 11

2 Answers2

4

If you want to work with an array which dimension is not known at the compile time, I would suggest you to recursively process all of its entries instead of trying to cast it.

You can use object.getClass().isArray() method to check if the current entry is an array and then iterate over it using Array.getLength(object) and Array.get(object, i):

public static void main(String[] args) {
    Object array = new String[][] {new String[] {"a", "b"}, new String[] {"c", "d"}};
    processArray(array, System.out::println);
}

public static void processArray(Object object, Consumer<Object> processor) {
    if (object != null && object.getClass().isArray()) {
        int length = Array.getLength(object);
        for (int i = 0; i < length; i ++) {
            Object arrayElement = Array.get(object, i);
            processArray(arrayElement, processor);
        }
    } else {
        processor.accept(object);
    }
}
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
0

If the size of the array is not known statically (at compile time), then it's logically impossible to get the length relying solely on static means, i.e. without use of dynamic means.

Perhaps this question has the solution you need: Getting the field "length" in a Java array using reflection

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111