一步生成树形结构(自定义工具类实现)
前言
在日常工作中,我们经常会遇到需要生成树形结构的需求,例如:部门树、菜单树等,我们以往的实现方式是写一个递归算法来实现,但是如果这样的需求多了,我们难不成要给每个需求都写一个递归算法来实现吗?显然这是不合理的,我们这样操作会造成很多的冗余代码。那么我们有没有更好的实现思路呢?在这里我分享一种思路,也欢迎大家来一起讨论
实现
思路剖析
我们理想状态是写一个通用的工具类,那么问题来了,到底要咋写?
所以大家别着急,搬个小板凳坐好了,听我给你娓娓道来。接下来我先解答一下大家可能会问的问题。
Q: 你这不对,方法里传入的对象都不一样,你怎么进行对比?
A: 关于这个问题,咱们能用泛型来解决,这样就解决了传入对象不一致导致不能通用的问题。
Q: 那你如果用泛型的话,不就拿不到参数值了吗,你怎么对比?
A: 你别说,这其实也是这个思路的核心,拿小本本记好了:我们可以 在调用的时候把需要比对的名字传进去,再通过反射来拿到对应参数的值,拿到值之后我们再进行业务处理即可。
说干就干,兄弟们走,我们去实践一波。
实现
反射工具类:ReflectionUtils
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.*;
/**
* @author Bummon
* @date 2023-06-30 14:23:14
* @description 反射工具类
*/
@Slf4j
public class ReflectionUtils {
public ReflectionUtils() {
}
private static String getExceptionMessage(String fieldName,Object object){
return "Could not find field [" + fieldName + "] on target [" + object + "]";
}
/**
* @param object 操作对象
* @param fieldName 要取值的属性名
* @return {@link Object}
* @date 2023-06-30 14:19:32
* @author Bummon
* @description 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
*/
public static Object getFieldValue(Object object, String fieldName) {
Field field = getDeclaredField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException(getExceptionMessage(fieldName,object));
}
makeAccessible(field);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
log.error("getFieldValue:", e);
}
return result;
}
/**
* @param object 操作对象
* @param fieldName 设置值的属性名
* @param value 设置的值
* @date 2023-06-30 14:19:56
* @author Bummon
* @description 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
*/
public static void setFieldValue(Object object, String fieldName, Object value) {
Field field = getDeclaredField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException(getExceptionMessage(fieldName,object));
}
makeAccessible(field);
try {
field.set(object, value);
} catch (IllegalAccessException e) {
log.error("setFieldValue:", e);
}
}
/**
* @param clazz 类
* @param index 索引值
* @return {@link Class}
* @date 2023-06-30 14:20:29
* @author Bummon
* @description 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型 如: public EmployeeDao extends BaseDao<Employee, String>
*/
public static Class getSuperClassGenericType(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];
}
/**
* @param clazz 类
* @return {@link Class<T>}
* @date 2023-06-30 14:21:01
* @author Bummon
* @description 通过反射, 获得 Class 定义中声明的父类的泛型参数类型 如: public EmployeeDao extends BaseDao<Employee, String>
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getSuperGenericType(Class clazz) {
return getSuperClassGenericType(clazz, 0);
}
/**
* @param object 取值对象
* @param methodName 方法名
* @param parameterTypes 参数类型
* @return {@link Method}
* @date 2023-06-30 14:21:16
* @author Bummon
* @description 循环向上转型, 获取对象的 DeclaredMethod
*/
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;
}
/**
* @param field 需要设置允许访问的field
* @date 2023-06-30 14:21:44
* @author Bummon
* @description 设置field为允许访问
*/
public static void makeAccessible(Field field) {
if (!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
}
/**
* @param object 操作对象
* @param filedName field名
* @return {@link Field}
* @date 2023-06-30 14:22:13
* @author Bummon
* @description 循环向上转型, 获取对象的 DeclaredField
*/
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;
}
/**
* @param object 操作对象
* @param methodName 方法名
* @param parameterTypes 参数类型
* @param parameters 参数
* @return {@link Object}
* @date 2023-06-30 14:22:36
* @author Bummon
* @description 直接调用对象方法, 而忽略修饰符(private, protected)
*/
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;
}
构建树工具类:TreeUtils
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.