简体   繁体   English

如何反复迭代Array字段?

[英]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. 换句话说,首先使用Field.get从字段中获取值,然后使用java.lang.reflect.Array帮助程序类来访问长度和单个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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