Java Reflection isArray() always false

Go To


I got a question about Java Reflections: I have to checkout, if a certain field of a class is an array. But my problem is: If i run isArray() on the attribute of the class directly, it works. But if I use it in the way below, it won"t work. I guess because the "real" array is in this Field class? Any idea how i get it to work - I think there is missing a cast or sth like that? Thanks!

Field fields[] = object.getClass().getDeclaredFields();

for (Field field : fields) {
    if (field.getClass().isArray()) {
        //Always false.
2009-06-16 08:59
by NoName



2009-06-16 08:59
by akarnokd


Your code should read

Field fields[] = obj.getClass().getDeclaredFields();

for(Field field : fields) {
     //Actually works

Using field.getClass() as you are will always return Field.class or a Class instance of a subclass of Field*.

*My apologizes for such a confusingly worded sentence.

2009-06-16 09:05
by Kevin Montrose


You are testing the individual elements of Fields, rather than the array itself.

2009-06-16 09:04
by PaulJWilliams
Sorry I don't understand this at all. "Elements of Fields?" Arrays have elements. Fields don't - finnw 2009-10-12 16:57
'fields' as in the variable 'fields' - PaulJWilliams 2009-10-13 11:45