简体   繁体   中英

How do I iterate over an Array field reflectively?

I have

Class<? extends Object> class1 = obj.getClass();
    Field[] fields = class1.getDeclaredFields();
    for (Field aField : fields) {
      aField.setAccessible(true);
       if (aField.getType().isArray()) {
          for (?? vals : aField) {
            System.out.println(vals);
          }
        }
      }

You'd use something like this:

if (aField.getType().isArray()) {
  Object array = aField.get(obj);
  int length = Array.getLength(array);
  for (int i = 0; i < length; i++) {
    System.out.println(Array.get(array, i));
  }
}

In other words, you first fetch the value from the field using Field.get , then use the java.lang.reflect.Array helper class to access the length and the individual elements.

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