Hello!
I'm going through the fields of a class one at a time and need to handle
differently depending on whether they are arrays or scalars.
What's the right way to make the distinction? The snippet below fails to
detect arrays :(
Thanks!
-mi
import java.lang.reflect.*;
....
for (Field field : getClass().getFields()) {
Type type = field.getGenericType();
System.err.println("Type of " + field + " is " + type + type.getClass());
if (type instanceof GenericArrayType)
System.err.println(field + " is an array!");
else
System.err.println(field + " is not an array");
}
Robert Larsen - 12 Dec 2007 02:19 GMT
> Hello!
>
[quoted text clipped - 19 lines]
> System.err.println(field + " is not an array");
> }
robert-desktop:~ $ cat Test.java
import java.lang.reflect.*;
public class Test {
private int nonArray;
private int array[];
public Test() {
}
public static void main(String args[]) throws Exception {
Class c = Test.class;
for (Field f : c.getDeclaredFields()) {
System.out.println("Field: " + f + " Is array: " +
f.getType().isArray());
}
}
}
robert-desktop:~ $ javac Test.java
robert-desktop:~ $ java Test
Field: private int Test.nonArray Is array: false
Field: private int[] Test.array Is array: true
robert-desktop:~ $
Mikhail Teterin - 12 Dec 2007 17:03 GMT
> f.getType().isArray()
Many thanks!
-mi