栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java反射生成树工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java反射生成树工具类

Category类

@Data
@Builder
public class Category {
    private int id;
    private int parentId;
    private String name;

    private List children;
}

TreeUtils类

public class TreeUtils {

    public static void main(String[] args) throws Exception {
        List nodes = new ArrayList();
        nodes.add(Category.builder().id(1).parentId(0).name("电脑").build());
        nodes.add(Category.builder().id(2).parentId(1).name("dell").build());
        nodes.add(Category.builder().id(3).parentId(1).name("mac").build());
        nodes.add(Category.builder().id(4).parentId(2).name("pro").build());
        List list = generate(nodes, 0);
        System.out.println(JSONUtil.toJsonPrettyStr(list));
    }

    public static List generate(List nodes, int parentId)
            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        return generate(nodes, 0, null, null, null);
    }

    public static List generate(List nodes, int parentId, String idName, String pidName, String childrenName)
            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        if (StringUtils.isEmpty(idName)) {
            idName = "id";
        }
        if (StringUtils.isEmpty(pidName)) {
            pidName = "parentId";
        }
        if (StringUtils.isEmpty(childrenName)) {
            childrenName = "children";
        }
        if (nodes == null || nodes.size() <= 0) {
//            return Collections.emptyList();
            return null;
        }
        List list = new ArrayList();
        for (T node : nodes) {
            Class clazz = node.getClass();
            Field idField = clazz.getDeclaredField(idName);
            Field pidField = clazz.getDeclaredField(pidName);
            Field childrenField = clazz.getDeclaredField(childrenName);
            idField.setAccessible(true);
            pidField.setAccessible(true);
            childrenField.setAccessible(true);
            int id = idField.getInt(node);
            int pid = pidField.getInt(node);
            if (pid == parentId) {
                list.add(node);
                List children = generate(nodes, id, idName, pidName, childrenName);
                childrenField.set(node, children);
            }
        }
        return list;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/931038.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号