Java实现树形结构转换器
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections4.comparators.ComparatorChain;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HierarchyConvertUtils {
public static <T> List<T> convert(List<T> list, Object rootId) {
List<T> result = new ArrayList<>();
try {
for (T model : list) {
Class<?> aClass = model.getClass();
Method roleName = aClass.getMethod("getParentId");
if (rootId.equals(roleName.invoke(model))) {
Method childNodeMethod = aClass.getMethod("setChildNode", List.class);
Method idMethod = aClass.getMethod("getId");
T newModel = (T) BaseConvertUtils.toObject(model, model.getClass());
childNodeMethod.invoke(newModel, sortList(convert(list, idMethod.invoke(model))));
result.add(newModel);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("操作失败");
}
return sortList(result);
}
public static <T> List<T> convertHierarchy(List<T> list, Object rootId) {
return convert(list, rootId, 1);
}
private static <T> List<T> convert(List<T> list, Object rootId, Integer h) {
List<T> result = new ArrayList<>();
try {
for (T model : list) {
Class<?> aClass = model.getClass();
Method roleName = aClass.getMethod("getParentId");
if (rootId.equals(roleName.invoke(model))) {
Method childNodeMethod = aClass.getMethod("setChildNode", List.class);
Method idMethod = aClass.getMethod("getId");
T newModel = (T) BaseConvertUtils.toObject(model, model.getClass());
Method setHierarchy = aClass.getMethod("setHierarchy", Integer.class);
setHierarchy.invoke(newModel, h);
childNodeMethod.invoke(newModel, sortList(convert(list, idMethod.invoke(model), h + 1)));
result.add(newModel);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("操作失败");
}
return sortList(result);
}
private static <T> List<T> sortList(List<T> list) {
ComparatorChain compChain = new ComparatorChain();
compChain.addComparator(new BeanComparator("sort"), true);
Collections.sort(list, compChain);
return list;
}
}