小工具-集合构造树形结构
作者:互联网
/**
* 集合树形转换
*
* @param list 需要转换的集合
* @param tClass 集合中对象类型
* @param parentIdField 父节点字段
* @param nodeField 下级节点字段
* @param parentId 父节点
* @param <T> 集合中对象类型
* @return
* @throws NoSuchFieldException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static <T> List<T> getTree(List<T> list, Class<? extends T> tClass, String idField, String parentIdField, String nodeField, long parentId)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
List<T> result = new ArrayList<>();
//当前节点方法
idField = idField.replaceFirst(idField.substring(0, 1), idField.substring(0, 1).toUpperCase());
Method methodId = tClass.getMethod("get" + idField);
//父节点方法
parentIdField = parentIdField.replaceFirst(parentIdField.substring(0, 1), parentIdField.substring(0, 1).toUpperCase());
Method methodParent = tClass.getMethod("get" + parentIdField);
//下级节点方法
nodeField = nodeField.replaceFirst(nodeField.substring(0, 1), nodeField.substring(0, 1).toUpperCase());
Method methodNode = tClass.getMethod("set" + nodeField, List.class);
for (T t : list) {
long id = (long) methodId.invoke(t);
if (methodParent.invoke(t).equals(parentId)) {//找到下级节点
methodNode.invoke(t, getTree(list, tClass, idField, parentIdField, nodeField, id));
result.add(t);
}
}
return result;
}
方法直接可用,将list集合构造成为树形结构;当然也可以改造成为数组、Set、Map等集合形式。
标签:idField,parentIdField,nodeField,构造,substring,树形,param,集合,tClass 来源: https://blog.csdn.net/lj15559275886/article/details/115051115