package com. cfzq. lz. msg. util;
import java. lang. reflect. InvocationTargetException;
import java. util. ArrayList;
import java. util. List;
public class TreeUtils {
private static final String ROOT_ID = "0" ;
private static final String GET = "get" ;
private static final String SET = "set" ;
private TreeUtils ( ) {
throw new IllegalStateException ( "Utility class" ) ;
}
public static < T> List< T> buildByRecursive ( List< T> list, String idName, String parentIdName, String childrenName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
List< T> result = new ArrayList < > ( ) ;
for ( T t : list) {
String pId = reflect ( t. getClass ( ) , GET + parentIdName, t) . toString ( ) ;
if ( ROOT_ID. equals ( pId) ) {
result. add ( findChildren ( t, list, idName, parentIdName, childrenName) ) ;
}
}
return result;
}
public static < T> T findChildren ( T bean, List< T> beans, String idName, String parentIdName, String childrenName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String id = bean. getClass ( ) . getMethod ( GET + idName) . invoke ( bean) . toString ( ) ;
List< T> children = ( List) reflect ( bean. getClass ( ) , GET + childrenName, bean) ;
for ( T it : beans) {
String parentId = it. getClass ( ) . getMethod ( GET + parentIdName) . invoke ( it) . toString ( ) ;
if ( id. equals ( parentId) ) {
if ( children == null) {
bean. getClass ( ) . getMethod ( SET + childrenName, List. class ) . invoke ( bean, new ArrayList < > ( ) ) ;
}
children = ( List) reflect ( bean. getClass ( ) , GET + childrenName, bean) ;
children. add ( findChildren ( it, beans, idName, parentIdName, childrenName) ) ;
}
}
return bean;
}
public static < T> Object reflect ( Class clazz , String methodName, T t) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return clazz. getMethod ( methodName) . invoke ( t) ;
}
}
用法
List< User> msgTypeVos = TreeUtils. buildByRecursive ( list, "Id" , "Pid" , "ChildrenList" ) ;
实体
public class User ( ) {
private String id;
private String pid;
private List< User> childrenList;
get. . .
set. . .
}