在Java中遍历复杂的对象图并获取属性的索引(类似于xpath)

问题描述 投票:1回答:2

问题陈述:

想象一下如下的嵌套对象:

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

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

class Employee{
String name;
...
}

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

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

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

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

是否有一个好的开源库暴露类似的api或什么是最好的方法来遍历复杂的对象图

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

如果有人遇到类似需求,请提供建议

java javabeans jxpath
2个回答
1
投票

我还没有看到这样做的库,但你可以修改我的对象迭代器博客中的代码来执行此操作。

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

快乐的编码!


0
投票

你可以使用SOJO (Simplified Old Java Objects)

根据theirs documentation,我认为PathRecordWalkerInterceptor是你的搜索:

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

walker.walk(car);
Map visitedPathes = interceptor.getAllRecordedPathes();
© www.soinside.com 2019 - 2024. All rights reserved.