Lindstorm
Lindstorm

Reputation: 889

How do you iterate over an array that is referenced by Object?

I have a function get(String) that returns an Object based on an identifying string.

Sometimes, the Object returned from get is an array. If so, I would like to iterate over each array element and process that element somehow. Something like the following code.

 Object object = get(identifier);
 if(object.getClass().isArray())
      processArray(object);

 void processArray(Object array) {
    //For each element in the array, do something
 }

My attempted solution of this is something like

 void processArray(Object array) {
      Object[] arrayCasted  = (Object[]) array;
      for(Object arrayElement : arrayCasted)
           //Process each element somehow 
 }

But this only works for arrays of objects (and not primitive arrays)

 Integer[] test1 = {1, 2, 3};
 int[] test2 = {1, 2, 3};
 processArray(test1); //Works
 processArray(test2); //Does not work: ClassCastException

Is there anyway to make processArray work for all arrays?

Upvotes: 1

Views: 373

Answers (1)

fiveobjects
fiveobjects

Reputation: 4309

Use java.lang.reflect.Array is the key. If you have an Object which is actually an array of some type (primitive, String or some custom type, etc.) you can iterate over, print, etc. without knowing its type or doing typecasting, etc.

Typecasting to Object[] is not possible since the elelemnts are not of type Object but, you can typecast to specific type of array by knowing its component type (obj.getClass().getComponentType()). However, java.lang.reflect.Array based solution is much cleaner.

import java.lang.reflect.Array;

public class ArrayOfUnknownType {
    public static void main(String[] args) {
        int[] i = {1, 2, 3};
        String[] s = {"a", "b", "c"};
        Dog[] d = {new Dog("d"), new Dog("e")};
        process(i);
        process(s);
        process(d);
    }

    private static void process(Object data) {
        System.out.println(data.getClass().getComponentType());
        if(data.getClass().isArray()) {
            int length = Array.getLength(data);
            for(int count =0; count < length; count++ ){
                System.out.println(Array.get(data, count));
            }
        }
    }

    private static class Dog {
        public String name;

        public Dog(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Dog{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}

Upvotes: 3

Related Questions