2

问题陈述:

想象一个像下面这样的嵌套对象:

class Company{
...
List<Department> departments;
}

class Department{
...
List<Employee> employees;
}

class Employee{
String name;
...
}

一个公司有很多部门,每个部门都有很多员工。

Json 主体由库解组,以创建 Java 对象 Company,如上所示。

假设我有一个名为“John”的员工,我正在寻找一个 api,当我传入 Employee 对象的哈希或属性名称时,它会返回该属性的路径。

search(Object attributeName, Object attributeValue) 即 search("name", "John") 应该返回 company.departments[0].employees[5]

是否有一个很好的开源库公开类似的 api 或者什么是遍历复杂对象图的最佳方法

JSR 303 Hibernate Validator,它自动将属性路径添加到 ConstraintViolation 不会公开它如何通过任何对象从复杂对象图中获取属性路径的行为

如果有人遇到过类似的需求,请提出建议

4

2 回答 2

2

我还没有看到完全做到这一点的库,但您可以修改我的对象迭代器博客中的代码来做到这一点。

https://blog.stackhunter.com/2014/07/09/convert-java-objects-to-string-with-the-iterator-pattern/

迭代器导航对象图以产生如下所示的输出,但您可以让它做任何事情——包括搜索键值对。

com.stackhunter.example.employee.Department@129719f4
  deptId = 5775
  employeeList = java.util.ArrayList@7037717a
employeeList[0] = com.stackhunter.example.employee.Employee@17a323c0
  firstName = Bill
  id = 111
  lastName = Gates
employeeList[1] = com.stackhunter.example.employee.Employee@57801e5f
  firstName = Howard
  id = 222
  lastName = Schultz
employeeList[2] = com.stackhunter.example.employee.Manager@1c4a1bda
  budget = 75000.0
  firstName = Jeff
  id = 333
  lastName = Bezos
  name = Sales
[I@39df3255
  object[0] = 111
  object[1] = 222
  object[2] = 333

快乐编码!

于 2016-03-09T00:34:33.633 回答
1

您可以使用SOJO(简化的旧 Java 对象)

根据他们的文档,我认为PathRecordWalkerInterceptor您正在搜索的内容是:

Car car = new Car("Ferrari");
ObjectGraphWalker walker = new ObjectGraphWalker();
PathRecordWalkerInterceptor interceptor = new PathRecordWalkerInterceptor();
walker.addInterceptor(interceptor);

walker.walk(car);
Map visitedPathes = interceptor.getAllRecordedPathes();
于 2019-02-24T21:04:40.163 回答