由于某些原因,我需要一个新对象来包装从其他 API 获取的数据。
我面临的问题是不知道如何处理原始对象的递归字段。
这里是示例代码:
//original object
public class Resource{
private String name;
private String content;
private Integer type;
private List<Resource> children = new LinkedList();
public void addChildrenResource(Resource children) {
this.children.add(children);
}
//getters&setters...
}
<小时/>
//the object try to convert
public class Menu{
private String name;
private String url;
private Integer type;
private List<Menu> subMenu = new LinkedList();
public void addChildrenResource(Menu subMenu) {
this.children.add(subMenu);
}
//getters&setters...
}
<小时/>
我所做的实现,我不知道与递归字段有关......
这是我的代码..
List<Resource> resources = rpcService.getResources();
//Here I can't handle the subMenu or children part..
List<Menu> menus = resources.stream().map(r -> new Menu(r.getName(),
r.getContent(), r.getType())).collect(Collectors.toList());
<小时/>
递归可能有很多层,那么如何用递归字段转换呢?
注意:Resource
类来自另一个模块,因此我无法更改它,由于命名问题,我必须对其进行转换。
我们不必通过Stream()
来解决它,只需找到一种方法来解决即可。
最佳答案
您需要创建一个方法并递归调用该方法:
public static List<Menu> convert(List<Resource> resources) {
return resources == null ? null :
resources.stream()
.map(r -> new Menu(r.getName(), r.getContent(), r.getType(), convert(r.getChildren)))
.collect(Collectors.toList());
}
关于java - 使用java中的递归字段转换对象并包装到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52185275/