30

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

ahmed hamdy
  • 5,096
  • 1
  • 47
  • 58
Roman
  • 7,933
  • 17
  • 56
  • 72

4 Answers4

76

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)

Ralph
  • 118,862
  • 56
  • 287
  • 383
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
5

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

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
3

You can do

if (o instanceof Object[]) {
  Object[] array = (Object[]) o;
  // now access array.length or 
  // array.getClass().getComponentType()
}
Mr. Shiny and New 安宇
  • 13,822
  • 6
  • 44
  • 64
  • This is good , but it will not apply to the primitive array types. I think i found the answer : object.getClass().isArray() .. lol – Roman Feb 04 '10 at 14:46
0

First of all, @Bozho's answer is perfectly correct.

If you want to make this to be easier useable, I've just created a method in our little OSS utility molindo-utils that turns an array of unknown type into an Iterable: ArrayUtils.toIterable(Object)

This way, you can do:

// any array, e.g. int[], Object[], String[], ...
Object array = ...;
for (Object element : ArrayUtils.toIterable(array)) {
    // element of type Integer for int[]
    System.out.println(element);
}

See README of molindo-utils on how to get molindo-utils or feel free to copy the code if you like, just as you see fit.

sfussenegger
  • 35,575
  • 15
  • 95
  • 119