Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over arrays by reflection

I am doing some reflection work and go to a little problem.

I am trying to print objects to some GUI tree and have problem detecting arrays in a generic way.

I suggested that :

object instanceof Iterable

Would make the job ,but it does not, (obviously applies only to Lists and Set and whoever implements it.)

So how is that i would recognice an Array Some Object[] , Or long[] or Long[] .. ?

Thanks

like image 264
Roman Avatar asked Feb 04 '10 14:02

Roman


3 Answers

If you don't want only to check whether the object is an array, but also to iterate it:

if (array.getClass().isArray()) {
    int length = Array.getLength(array);
    for (int i = 0; i < length; i ++) {
        Object arrayElement = Array.get(array, i);
        System.out.println(arrayElement);
    }
}

(the class above is java.lang.reflect.Array)

like image 81
Bozho Avatar answered Nov 18 '22 00:11

Bozho


Do you mean Object.getClass().isArray()?

like image 32
Joonas Pulakka Avatar answered Nov 17 '22 22:11

Joonas Pulakka


You can do

if (o instanceof Object[]) {
  Object[] array = (Object[]) o;
  // now access array.length or 
  // array.getClass().getComponentType()
}
like image 3
Mr. Shiny and New 安宇 Avatar answered Nov 17 '22 22:11

Mr. Shiny and New 安宇