How to see if an object is an array without using reflection?

edbras picture edbras · Apr 28, 2010 · Viewed 109.9k times · Source

How can I see in Java if an Object is an array without using reflection? And how can I iterate through all items without using reflection?

I use Google GWT so I am not allowed to use reflection :(

I would love to implement the following methods without using refelection:

private boolean isArray(final Object obj) {
  //??..
}

private String toString(final Object arrayObject) {
  //??..
}

BTW: neither do I want to use JavaScript such that I can use it in non-GWT environments.

Answer

Steve Kuo picture Steve Kuo · Apr 28, 2010

You can use Class.isArray()

public static boolean isArray(Object obj)
{
    return obj!=null && obj.getClass().isArray();
}

This works for both object and primitive type arrays.

For toString take a look at Arrays.toString. You'll have to check the array type and call the appropriate toString method.