使用嵌套反射迭代包含 object 的 object
Use nested reflection to iterate an object that contains objects
如标题所示,我需要使用反射迭代 object。我有什么:
@Getter
@Setter
public static class ObjectA {
public ObjectB obj;
}
@Getter
@Setter
public static class ObjectB {
public String value;
}
String pathValueRetrived = "ObjectA.obj.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);
}
非常感谢您的帮助!
你或许可以通过递归来实现:
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
);
}
一些笔记:
- 没有实际的错误处理:您可能需要自己实现,当前的解决方案只是将所有内容向上抛给调用者
- 没有正确的输入验证:即如果
path
在字符串的开头或结尾包含句点。
- 未测试
如标题所示,我需要使用反射迭代 object。我有什么:
@Getter
@Setter
public static class ObjectA {
public ObjectB obj;
}
@Getter
@Setter
public static class ObjectB {
public String value;
}
String pathValueRetrived = "ObjectA.obj.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);
}
非常感谢您的帮助!
你或许可以通过递归来实现:
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
);
}
一些笔记:
- 没有实际的错误处理:您可能需要自己实现,当前的解决方案只是将所有内容向上抛给调用者
- 没有正确的输入验证:即如果
path
在字符串的开头或结尾包含句点。 - 未测试