商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Java通过注解实现构建树结构工具类

Java通过注解实现构建树结构工具类

  发布于2026-07-01 阅读(0)

扫一扫,手机访问

前言

Ja va注解这东西,大家都不陌生。说到底,注解就是附加在代码上的一种元数据,它本身不改变程序的逻辑,却能给代码注入额外的信息——配置、验证、文档,甚至驱动一些自动化的逻辑处理。这篇文章要聊的,就是怎么用注解来构建一棵树结构。用注解来做这个事,具体怎么操作?直接往下看。

Ja va通过注解实现构建树结构工具类

别绕弯子,直接开搞。

枚举类

先定义一下字段的数据类型。这么做的目的很简单:注解需要知道自己标注的字段是什么类型,这样在反射取值时才能做正确的类型转换。

public enum DataType {
    /** long */
    LONG,

    /** string */
    STRING,

    /** LIST */
    LIST,
}

注解

接下来定义三个核心注解,分别标记主键、父节点ID和子节点集合。每个注解都通过dataType属性来指定数据类型,默认值分别对应最常见的场景。

标记主键的注解:

	
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PrimaryKey {

    /** 字段数据类型默认为 long */
    DataType dataType() default DataType.LONG;
}

标记父节点ID的注解:

	
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ParentKey {
    
    /** 字段数据类型默认为 long */
    DataType dataType() default DataType.LONG;
}

标记子节点集合的注解:

	
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ChildrenKey {

    /** 字段数据类型默认为 List */
    DataType dataType() default DataType.LIST;
}

获取注解标识的字段值

有了注解,得有个工具把它们标注的字段值取出来。这步其实不复杂,就是利用反射遍历类的所有字段,找到标注了指定注解的那一个,然后获取它的值。AnnotationUtil 就干这一件事。

public class AnnotationUtil {

    /**
     * 获取注解 annotation 标识的字段值
     * @param t entity
     * @param annotation 注解
     * @return ja va.lang.Object
     */
    public static  Object getFieldValue(T t, Class annotation) throws IllegalAccessException {
        Object fieldValue = null;
        Class clazz = t.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if(field.isAnnotationPresent(annotation)){
                field.setAccessible(true);
                fieldValue = field.get(t);
                break;
            }
        }
        return fieldValue;
    }
}

构建树结构工具类

工具类TreeUtils才是重头戏,它负责把平铺的数据列表转化成树形结构。核心思路是:找到所有顶级节点(即父ID不在主键集合中的节点),然后挨个递归查找它们的子节点。这里给Long和String两种主键类型分别做了实现,代码逻辑一致,只是类型处理不同。

public class TreeUtils {
    private static final Logger log = LoggerFactory.getLogger(TreeUtils.class);

    /**
     * 构建前端所需要树结构,主键为 Long 时
     * @param tList 数据集
     * @return ja va.util.List 树结构列表
     */
    public static  List buildLongTree(List tList) {
        try {
            List returnList = new ArrayList<>();
            //主键id集合
            List tempList = new ArrayList<>();
            for (T t : tList) {
                Long primaryId = (Long) AnnotationUtil.getFieldValue(t, PrimaryKey.class);
                tempList.add(primaryId);
            }
            for (T t : tList) {
                // 如果是顶级节点, 遍历该父节点的所有子节点
                Long parentId = (Long) AnnotationUtil.getFieldValue(t, ParentKey.class);
                if (!tempList.contains(parentId)) {
                    recursionLong(tList, t);
                    returnList.add(t);
                }
            }
            if (returnList.isEmpty()) {
                returnList = tList;
            }
            return returnList;
        } catch (Exception e) {
            log.error("树结构转换失败:{}", e.getMessage());
            return tList;
        }
    }

    /**
     * 构建前端所需要树结构,主键为 String 时
     * @param tList 数据集
     * @return ja va.util.List 树结构列表
     */
    public static  List buildStringTree(List tList) {
        try {
            List returnList = new ArrayList<>();
            List tempList = new ArrayList<>();
            for (T t : tList) {
                String primaryId = (String) AnnotationUtil.getFieldValue(t, PrimaryKey.class);
                tempList.add(primaryId);
            }
            for (T t : tList) {
                // 如果是顶级节点, 遍历该父节点的所有子节点
                String parentId = (String) AnnotationUtil.getFieldValue(t, ParentKey.class);
                if (!tempList.contains(parentId)) {
                    recursionString(tList, t);
                    returnList.add(t);
                }
            }
            if (returnList.isEmpty()) {
                returnList = tList;
            }
            return returnList;
        } catch (IllegalAccessException e) {
            log.error("树结构转换失败:{}", e.getMessage());
            return tList;
        }
    }

    /**
     * 递归设置子集数据,主键为 Long 时
     * @param list 数据集合
     * @param o 对象
     */
    private static  void recursionLong(List list, Object o) throws IllegalAccessException {
        // 得到子节点列表
        List childList = getLongChildList(list, o);
        invokeChildrenList(o, childList);

        for (Object oChild : childList) {
            if (getLongChildList(list, oChild).size() > 0) {
                recursionLong(list, oChild);
            }
        }
    }

    /**
     * 递归设置子集数据,主键为 String 时
     * @param list 数据集合
     * @param o 对象
     */
    private static  void recursionString(List list, Object o) throws IllegalAccessException {
        // 得到子节点列表
        List childList = getStringChildList(list, o);
        invokeChildrenList(o, childList);

        for (Object oChild : childList) {
            if (getStringChildList(list, oChild).size() > 0) {
                recursionString(list, oChild);
            }
        }
    }

    /**
     * 得到子节点列表,主键为 Long 时
     * @param list 数据
     * @param object entity
     * @return ja va.util.List
     */
    private static  List getLongChildList(List list, Object object) throws IllegalAccessException {
        Long primaryId = (Long) AnnotationUtil.getFieldValue(object, PrimaryKey.class);

        List objects = new ArrayList<>();
        for (T o : list) {
            Long parentId = (Long) AnnotationUtil.getFieldValue(o, ParentKey.class);
            if (null != parentId && parentId.longValue() == primaryId.longValue()) {
                objects.add(o);
            }
        }
        return objects;
    }

    /**
     * 得到子节点列表,主键为 String 时
     * @param list 数据
     * @param object entity
     * @return ja va.util.List
     */
    private static  List getStringChildList(List list, Object object) throws IllegalAccessException {
        String primaryId = (String) AnnotationUtil.getFieldValue(object, PrimaryKey.class);

        List objects = new ArrayList<>();
        for (T o : list) {
            String parentId = (String) AnnotationUtil.getFieldValue(o, ParentKey.class);
            if (null != parentId && parentId.equals(primaryId)) {
                objects.add(o);
            }
        }
        return objects;
    }

    /**
     * 通过反射设置子集数据
     * @param o 对象
     * @param childList 子集数据
     */
    private static  void invokeChildrenList(Object o, List childList) {
        Class clazz = o.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if(field.isAnnotationPresent(ChildrenKey.class)){
                field.setAccessible(true);
                ReflectUtils.invokeSetter(o, field.getName(), childList);
                break;
            }
        }
    }

}

测试一下

理论说完了,拿一个部门树来跑跑看。定义一个Dept类,三个核心字段全都用注解标记好。主键和父ID是Long型,子集是List型,跟注解的默认值一致。

// 此处使用lombok减少代码
@Data
public class Dept implements Serializable {
    private static final long serialVersionUID = -1L;

    /**
     * 部门ID
     * 如果数据类型为字符串,则 @PrimaryKey(dataType = DataType.STRING)
     */  
    @PrimaryKey
    private Long deptId;

    /** 
     * 父部门ID
     * 如果数据类型为字符串,则 @ParentKey(dataType = DataType.STRING)
     */
    @ParentKey
    private Long parentId;

    /** 部门名称 */
    private String deptName;

    /** 子部门 */
    @ChildrenKey
    private List children = new ArrayList<>();

    /** 加一个有参构造,方便测试 */
    public Dept(Long deptId, Long parentId, String deptName) {
        this.deptId = deptId;
        this.parentId = parentId;
        this.deptName = deptName;
    }
}
@Test
public void test(){
    List deptList = new ArrayList<>();
    deptList.add(new Dept(1L, 0L, "部门0-1"));
    deptList.add(new Dept(2L, 0L, "部门0-2"));
    deptList.add(new Dept(3L, 1L, "部门1-1"));
    deptList.add(new Dept(4L, 1L, "部门1-2"));
    deptList.add(new Dept(5L, 2L, "部门2-1"));
    deptList.add(new Dept(6L, 2L, "部门2-2"));
    deptList.add(new Dept(7L, 3L, "部门1-1-1"));
    deptList.add(new Dept(8L, 3L, "部门1-1-2"));
    deptList.add(new Dept(9L, 6L, "部门2-2-1"));
    deptList.add(new Dept(10L, 6L, "部门2-2-2"));
    List depts = TreeUtils.buildLongTree(deptList);
    System.out.println(JSON.toJSONString(depts));
}

结果输出如下,嵌套关系完全正确:

[{
    "deptId": 1,
    "parentId": 0,
    "deptName": "部门0-1",
    "children": [{
        "deptId": 3,
        "parentId": 1,
        "deptName": "部门1-1",
        "children": [{
            "deptId": 7,
            "parentId": 3,
            "deptName": "部门1-1-1",
            "children": []
        }, {
            "deptId": 8,
            "parentId": 3,
            "deptName": "部门1-1-2",
            "children": []
        }]
    }, {
        "deptId": 4,
        "parentId": 1,
        "deptName": "部门1-2",
        "children": []
    }]
}, {
    "deptId": 2,
    "parentId": 0,
    "deptName": "部门0-2",
    "children": [{
        "deptId": 5,
        "parentId": 2,
        "deptName": "部门2-1",
        "children": []
    }, {
        "deptId": 6,
        "parentId": 2,
        "deptName": "部门2-2",
        "children": [{
            "deptId": 9,
            "parentId": 6,
            "deptName": "部门2-2-1",
            "children": []
        }, {
            "deptId": 10,
            "parentId": 6,
            "deptName": "部门2-2-2",
            "children": []
        }]
    }]
}]

以上就是基于Ja va注解构建树结构工具类的完整思路。用注解的关键优势在于,它能给字段贴上明确的语义标签,代码读起来清晰,维护时也省心——改动字段含义时,只需要调整注解配置,而无需修改树构建的核心逻辑。

本文转载于:https://www.jb51.net/program/364033g02.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注