用到时,找的时间比撸的时间还长,节省时间记录一下
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 转树形结构工具类
*
* @Author: LSL
* @Date: 2022/3/22 17:51
* @Description:
*/
@Component
@Slf4j
public class TreeUtil<T> {
public List<T> tree;
/**
* @param treeData 数据
* @param rootId 根节点id
* @return
*/
public List<Object> treeMenu(List<T> treeData, String rootId) {
this.tree = treeData;
return child(rootId);
}
public List<Object> child(String id) {
List<Object> lists = new ArrayList<Object>();
for (T treeNode : tree) {
Map<String, Object> childArray = new LinkedHashMap<String, Object>();
try {
//获取父节点id
Field f = treeNode.getClass().getDeclaredField("pId");
f.setAccessible(true);
Object pId = f.get(treeNode);
if (pId.equals(id)) {
setTreeMap(childArray, treeNode);
lists.add(childArray);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
log.error(e.getMessage(), e);
}
}
return lists;
}
private void setTreeMap(Map<String, Object> mapArr, T treeNode) {
try {
//获取所有属性字段,组装
Field[] fs = treeNode.getClass().getDeclaredFields();
for (Field f : fs) {
f.setAccessible(true);
String name = f.getName();
Object o = f.get(treeNode);
mapArr.put(name, o);
if ("children".equals(f.getName())) {
Field field = treeNode.getClass().getDeclaredField("id");
field.setAccessible(true);
Object obj = field.get(treeNode);
mapArr.put("children", child(String.valueOf(obj)));
}
}
} catch (NoSuchFieldException | IllegalAccessException e) {
log.error(e.getMessage(), e);
}
}
}
/**
*实体类XXX至少包含id,pId,children三个属性字段
*/
List<Object> treeData = treeUtil.treeMenu(roleArr.toJavaList(XXX.class),"0");