反射构建菜单树
前提 数据库列表数据不超过100条 超过可能存在性能问题
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* 反射构建菜单树通用
* 目前仅支持integer类型和string类型 后续其他类型自行扩展
* 使用方法 : 直接调用即可
* @param <E>
*/
public class Tree<E> {
/**
* @param t 数据list集合
* @param pid 根节点父id
* @param tableId 树节点唯一id
* @param tableParentId 树节点父id
* @param children 子集名称
* @param <T> 泛型集合
* @return
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public <T> List<T> createTree(List<T> t, E pid,String tableId,String tableParentId,String children) throws NoSuchFieldException, IllegalAccessException {
List<T> newList = new ArrayList<>();
for (int i = 0; i < t.size(); i++) {
T t1 = t.get(i);
Class<?> aClass = t1.getClass();
Field id = aClass.getDeclaredField(tableId);
Class<?> type = id.getType();
id.setAccessible(true);
if(type.getTypeName().equals("java.lang.String")){
String id1 = id.get(t1).toString();
Field parentId = aClass.getDeclaredField(tableParentId);
parentId.setAccessible(true);
String parentId1 = parentId.get(t1).toString();
if(parentId1.equals(pid)){
Field roleList1 = aClass.getDeclaredField(children);
roleList1.setAccessible(true);
roleList1.set(t1,createTree(t,(E)id1,tableId,tableParentId,children));
newList.add(t1);
}
}else{
Integer id1 = (Integer) id.get(t1);
Field parentId = aClass.getDeclaredField(tableParentId);
parentId.setAccessible(true);
Integer parentId1 = (Integer) parentId.get(t1);
if(parentId1 == pid){
Field roleList1 = aClass.getDeclaredField(children);
roleList1.setAccessible(true);
roleList1.set(t1,createTree(t,(E)id1,tableId,tableParentId,children));
newList.add(t1);
}
}
}
return newList;
}
}