开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜