简体   繁体   中英

Java Reflection isArray() always false

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.
    }
}

Your code should read

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

for(Field field : fields) {
  if(field.getType().isArray()){
     //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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM