2021-05-18

反射构建菜单树

前提 数据库列表数据不超过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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值