- 前言:
- 由于上一篇博客只针对于实体TreeNode组装树形结构,但是实际开发中,我们对应数据表会创建很多实体来承载数据,反成不能每一种实体都需要写个递归或者循环的方法来组装数据结构吧?下面我将上一拼博客中的方法再进一步封装一下,封装成一个工具类,应对与所有的实体,但是这些实体中,必须含有HashSet类型的 children 成员变量,并生成 get set 方法;必须含有String类型的 id,parentId 成员变量,并且生成get set 方法。
/**
* 使用递归方法建树
* @param
* @return
*/
public static <T> List<T> buildTree(List<T> list) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, IntrospectionException {
List<T> trees = new ArrayList<>();
for (T treeNode : list) {
Method method = treeNode.getClass().getDeclaredMethod("getParentId", null);
Object value = method.invoke(treeNode, null);
if ("0".equals(String.valueOf(value))) {
trees.add(findChildren(treeNode,list));
}
}
return trees;
}
public static <T> T findChildren(T t,List<T> treeNodes) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IntrospectionException {
Method getIdMethod = t.getClass().getDeclaredMethod("getId");
String id = String.valueOf(getIdMethod.invoke(t, null));
for (T it : treeNodes) {
Method getParentIdMethod = it.getClass().getDeclaredMethod("getParentId");
Object parentId = getParentIdMethod.invoke(it, null);
if (id.equals(String.valueOf(parentId))) {
Method getChildrenMethod = t.getClass().getDeclaredMethod("getChildren");
Object children = getChildrenMethod.invoke(t, null);
if (null == children ) {
Method setChildrenMethod = t.getClass().getDeclaredMethod("setChildren",HashSet.class);
setChildrenMethod.invoke(t, new HashSet<T>());
}
((HashSet<T>)getChildrenMethod.invoke(t, null)).add(findChildren(it, treeNodes));
}
}
return t;
}
小结:
以上就是封装的工具类,本篇博客只是学习笔记使用,大家有更好的idea欢迎交流,请喷子远离!