递归查询树状结构树,通过反射设置

递归工具类:



import java.util.List;
import java.util.stream.Collectors;

/**
 * 通用属性结构工具类
 */
public class TreeUtils {


    /**
     * 通过父亲id=0 从一级开始往下排的方法
     */


    public static <T> List<T> bulidTree(List<T> list) {
        //通过反射拿到一级分类
        List<T> root = list.stream().filter(item -> (Long) ReflectionUtils.getFieldValue(item, "parentId") == 0).collect(Collectors.toList());
        list.removeAll(root);
        root.forEach(item->{
            getChildren(item,list);
        });

        return root;

    }

    /**
     * 递归 找孩子
     */
    public static <T> void getChildren(T t, List<T> list) {
        if (hasChildren(t,list)){
            List<T> collect = list.stream().filter(item -> (Long) ReflectionUtils.getFieldValue(item, "parentId") == (Long) ReflectionUtils.getFieldValue(t, "id")).collect(Collectors.toList());
            ReflectionUtils.setFieldValue(t,"children",collect);
            list.removeAll(collect);
            //遍历二级
            collect.forEach(item1->getChildren(item1,list));



        }


    }

    /**
     * 判断有没有孩子
     */
    public static <T> boolean hasChildren(T t, List<T> list) {
        //使用anyMath 来判断
        return list.stream().anyMatch(item -> {
            long a = (Long) ReflectionUtils.getFieldValue(item, "parentId");
            long b = (Long) ReflectionUtils.getFieldValue(t, "id");
            return a == b;

        });

    }


}

反射工具类:



import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.*;

@Slf4j//lombok中的日志
public class ReflectionUtils {
/**
 * 反射调用方法
 */
    /**
     * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
     *
     * @param object
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object object, String fieldName) {
        Field field = getDeclaredField(object, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }

        makeAccessible(field);

        Object result = null;

        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            log.error("getFieldValue:", e);
        }

        return result;
    }

    /**
     * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
     *
     * @param object
     * @param fieldName
     * @param value
     */
    public static void setFieldValue(Object object, String fieldName, Object value) {
        Field field = getDeclaredField(object, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }

        makeAccessible(field);

        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {
            log.error("setFieldValue:", e);
        }
    }


    /**
     * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     *
     * @param clazz
     * @param index
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Class getSuperClassGenricType(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            return Object.class;
        }

        if (!(params[index] instanceof Class)) {
            return Object.class;
        }

        return (Class) params[index];
    }

    /**
     * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     *
     * @param <T>
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getSuperGenericType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredMethod
     *
     * @param object
     * @param methodName
     * @param parameterTypes
     * @return
     */
    public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {

        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                //Method 不在当前类定义, 继续向上转型
            }
        }

        return null;
    }

    /**
     * 使 filed 变为可访问
     *
     * @param field
     */
    public static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers())) {
            field.setAccessible(true);
        }
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredField
     *
     * @param object
     * @param filedName
     * @return
     */
    public static Field getDeclaredField(Object object, String filedName) {

        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredField(filedName);
            } catch (NoSuchFieldException e) {
                //Field 不在当前类定义, 继续向上转型
            }
        }
        return null;
    }

    /**
     * 直接调用对象方法, 而忽略修饰符(private, protected)
     *
     * @param object
     * @param methodName
     * @param parameterTypes
     * @param parameters
     * @return
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     */
    public static Object invokeMethod(Object object, String methodName, Class<?>[] parameterTypes,
                                      Object[] parameters) {
        try {
            Method method = getDeclaredMethod(object, methodName, parameterTypes);
            if (method == null) {
                throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
            }
            method.setAccessible(true);
            return method.invoke(object, parameters);
        } catch (Exception e) {
            log.error("invokeMethod:", e);
        }
        return null;
    }
}

查找树桩结构时候,需要实体类增加字段获取children 数组

  /**
     * 是否有孩子
     */
    Boolean hasChildren;

    /**
     * 孩子 树状结构
     */
    List<DeptVo> children;

    /**
     * 是否是叶子节点  结果和hasChildren相反的值
     */

    Boolean isLeaf;

数据库设计:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值