views:

209

answers:

3

Hi Everyone

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

+1  A: 

You can do

if (o instanceof Object[]) {
  Object[] array = (Object[]) o;
  // now access array.length or 
  // array.getClass().getComponentType()
}
Mr. Shiny and New
This is good , but it will not apply to the primitive array types. I think i found the answer : object.getClass().isArray() .. lol
Roman
+5  A: 

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

Joonas Pulakka
+5  A: 

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)

Bozho