【问题标题】:Use nested reflection to iterate an object that contains objects使用嵌套反射迭代包含对象的对象
【发布时间】:2021-05-31 21:37:17
【问题描述】:

从标题中我需要使用反射来迭代一个对象。我有什么:

@Getter
@Setter
public static class ObjectA {
     public ObjectB obj;
}

@Getter
@Setter
public static class ObjectB {
     public String value;
}

String pathValueRetrived = "ObjectA.obj.value";

我必须以通用方式检索 value 属性。

类似:

String[] pathValue = StringUtils.split(pathValueRetrived, ".");
ObjectA objectA = //retrive the object with values
Object iterator;
for(String idxPath : pathValue){
  if(iterator != null)
      iterator = iterator.getClass().getDeclaredField(path);
  else
      iterator = objectA.getClass().getDeclaredField(path);
}

非常感谢您的帮助!

【问题讨论】:

  • 另外,请仅使用您实际使用的 java 版本标记您的问题。 提供确切的 java 版本也可以,因为您不会将自己限制为特定于版本的语言功能
  • 我刚刚编辑过。谢谢!

标签: java reflection


【解决方案1】:

你或许可以通过递归来实现:

public static Object getValue(Object target, String path) throws Exception {
    int index = path.indexOf('.');
    // if we don't find a period (.) or the target is null
    // then just return the target
    if (index < 0 || target == null) {
        return target;
    }
    // get the field name
    String field = path.substring(0, index);
    // get hold of the actual field
    Field field = target.getClass().getDeclaredField(field);
    // used if the field is private
    field.trySetAccessible();
    // recursive call
    return getValue(
        field.get(target),        // gets the value of the field, which is the new target
        path.substring(index + 1) // returns the substring after the found index
    );
}

一些注意事项

  1. 没有实际的错误处理:您可能需要自己实现,当前的解决方案只是将所有内容都向上抛给调用者
  2. 没有正确的输入验证:即如果path 在字符串的开头或结尾包含句点。
  3. 未测试

【讨论】:

  • 缺少了一个相当关键的位:getDeclaredField 在这里没有做你想做的事。您需要对父辈进行while循环,因为getDeclaredField 不会从您的超类中获取您的字段。 getField 确实如此,但是那个不会让您获得私有/包私有字段。如果您想要层次结构中的所有字段(甚至(包)私有),那么while循环是唯一的答案。
猜你喜欢
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
  • 2016-07-13
相关资源
最近更新 更多