最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java通過(guò)注解實(shí)現(xiàn)構(gòu)建樹(shù)結(jié)構(gòu)工具類(lèi)

 更新時(shí)間:2026年05月18日 08:51:02   作者:RainCity  
在Java中,注解是一種元數(shù)據(jù),可以提供有關(guān)代碼的附加信息,通過(guò)使用注解可以在代碼中添加配置信息、驗(yàn)證條件、文檔和其他信息,本文我們就來(lái)看如何使用注解實(shí)現(xiàn)構(gòu)建樹(shù)結(jié)構(gòu)吧

前言

在Java中,注解是一種元數(shù)據(jù),可以提供有關(guān)代碼的附加信息。通過(guò)使用注解,可以在代碼中添加配置信息、驗(yàn)證條件、文檔和其他信息,這使得代碼更易于理解和維護(hù)。在本文中,我將介紹如何使用Java注解構(gòu)建樹(shù)結(jié)構(gòu)工具類(lèi)。

話(huà)不多說(shuō),現(xiàn)在開(kāi)搞======================>

枚舉類(lèi)

標(biāo)識(shí)字段的數(shù)據(jù)類(lèi)型

	public enum DataType {
	    /** long */
	    LONG,
	
	    /** string */
	    STRING,
	
	    /** LIST */
	    LIST,
	}
	

注解

標(biāo)識(shí)字段為主鍵

	
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public @interface PrimaryKey {
	
	    /** 字段數(shù)據(jù)類(lèi)型默認(rèn)為 long */
	    DataType dataType() default DataType.LONG;
	}
	

標(biāo)識(shí)字段為父id

	
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public @interface ParentKey {
	    
	    /** 字段數(shù)據(jù)類(lèi)型默認(rèn)為 long */
	    DataType dataType() default DataType.LONG;
	}
	

標(biāo)識(shí)字段為子集

	
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public @interface ChildrenKey {
	
	    /** 字段數(shù)據(jù)類(lèi)型默認(rèn)為 List */
	    DataType dataType() default DataType.LIST;
	}
	

獲取注解標(biāo)識(shí)的字段值

public class AnnotationUtil {

    /**
     * 獲取注解 annotation 標(biāo)識(shí)的字段值
     * @param t entity
     * @param annotation 注解
     * @return java.lang.Object
     */
    public static <T> Object getFieldValue(T t, Class<? extends Annotation> 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;
    }
}

構(gòu)建樹(shù)結(jié)構(gòu)工具類(lèi)

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

    /**
     * 構(gòu)建前端所需要樹(shù)結(jié)構(gòu),主鍵為 Long 時(shí)
     * @param tList 數(shù)據(jù)集
     * @return java.util.List<T> 樹(shù)結(jié)構(gòu)列表
     */
    public static <T> List<T> buildLongTree(List<T> tList) {
        try {
            List<T> returnList = new ArrayList<>();
            //主鍵id集合
            List<Long> tempList = new ArrayList<>();
            for (T t : tList) {
                Long primaryId = (Long) AnnotationUtil.getFieldValue(t, PrimaryKey.class);
                tempList.add(primaryId);
            }
            for (T t : tList) {
                // 如果是頂級(jí)節(jié)點(diǎn), 遍歷該父節(jié)點(diǎn)的所有子節(jié)點(diǎn)
                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("樹(shù)結(jié)構(gòu)轉(zhuǎn)換失敗:{}", e.getMessage());
            return tList;
        }
    }

    /**
     * 構(gòu)建前端所需要樹(shù)結(jié)構(gòu),主鍵為 String 時(shí)
     * @param tList 數(shù)據(jù)集
     * @return java.util.List<T> 樹(shù)結(jié)構(gòu)列表
     */
    public static <T> List<T> buildStringTree(List<T> tList) {
        try {
            List<T> returnList = new ArrayList<>();
            List<String> tempList = new ArrayList<>();
            for (T t : tList) {
                String primaryId = (String) AnnotationUtil.getFieldValue(t, PrimaryKey.class);
                tempList.add(primaryId);
            }
            for (T t : tList) {
                // 如果是頂級(jí)節(jié)點(diǎn), 遍歷該父節(jié)點(diǎn)的所有子節(jié)點(diǎn)
                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("樹(shù)結(jié)構(gòu)轉(zhuǎn)換失?。簕}", e.getMessage());
            return tList;
        }
    }

    /**
     * 遞歸設(shè)置子集數(shù)據(jù),主鍵為 Long 時(shí)
     * @param list 數(shù)據(jù)集合
     * @param o 對(duì)象
     */
    private static <T> void recursionLong(List<T> list, Object o) throws IllegalAccessException {
        // 得到子節(jié)點(diǎn)列表
        List<T> childList = getLongChildList(list, o);
        invokeChildrenList(o, childList);

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

    /**
     * 遞歸設(shè)置子集數(shù)據(jù),主鍵為 String 時(shí)
     * @param list 數(shù)據(jù)集合
     * @param o 對(duì)象
     */
    private static <T> void recursionString(List<T> list, Object o) throws IllegalAccessException {
        // 得到子節(jié)點(diǎn)列表
        List<T> childList = getStringChildList(list, o);
        invokeChildrenList(o, childList);

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

    /**
     * 得到子節(jié)點(diǎn)列表,主鍵為 Long 時(shí)
     * @param list 數(shù)據(jù)
     * @param object entity
     * @return java.util.List<T>
     */
    private static <T> List<T> getLongChildList(List<T> list, Object object) throws IllegalAccessException {
        Long primaryId = (Long) AnnotationUtil.getFieldValue(object, PrimaryKey.class);

        List<T> 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;
    }

    /**
     * 得到子節(jié)點(diǎn)列表,主鍵為 String 時(shí)
     * @param list 數(shù)據(jù)
     * @param object entity
     * @return java.util.List<T>
     */
    private static <T> List<T> getStringChildList(List<T> list, Object object) throws IllegalAccessException {
        String primaryId = (String) AnnotationUtil.getFieldValue(object, PrimaryKey.class);

        List<T> 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;
    }

    /**
     * 通過(guò)反射設(shè)置子集數(shù)據(jù)
     * @param o 對(duì)象
     * @param childList 子集數(shù)據(jù)
     */
    private static <T> void invokeChildrenList(Object o, List<T> 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;
            }
        }
    }

}

測(cè)試一下

部門(mén) dept 類(lèi)

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

    /**
     * 部門(mén)ID
     * 如果數(shù)據(jù)類(lèi)型為字符串,則 @PrimaryKey(dataType = DataType.STRING)
     */  
    @PrimaryKey
    private Long deptId;

    /** 
     * 父部門(mén)ID
     * 如果數(shù)據(jù)類(lèi)型為字符串,則 @ParentKey(dataType = DataType.STRING)
     */
    @ParentKey
    private Long parentId;

    /** 部門(mén)名稱(chēng) */
    private String deptName;

    /** 子部門(mén) */
    @ChildrenKey
    private List<Dept> children = new ArrayList<>();

	/** 加一個(gè)有參構(gòu)造,方便測(cè)試 */
    public Dept(Long deptId, Long parentId, String deptName) {
        this.deptId = deptId;
        this.parentId = parentId;
        this.deptName = deptName;
    }
}
@Test
public void test(){
    List<Dept> deptList = new ArrayList<>();
    deptList.add(new Dept(1L, 0L, "部門(mén)0-1"));
    deptList.add(new Dept(2L, 0L, "部門(mén)0-2"));
    deptList.add(new Dept(3L, 1L, "部門(mén)1-1"));
    deptList.add(new Dept(4L, 1L, "部門(mén)1-2"));
    deptList.add(new Dept(5L, 2L, "部門(mén)2-1"));
    deptList.add(new Dept(6L, 2L, "部門(mén)2-2"));
    deptList.add(new Dept(7L, 3L, "部門(mén)1-1-1"));
    deptList.add(new Dept(8L, 3L, "部門(mén)1-1-2"));
    deptList.add(new Dept(9L, 6L, "部門(mén)2-2-1"));
    deptList.add(new Dept(10L, 6L, "部門(mén)2-2-2"));
    List<Dept> depts = TreeUtils.buildLongTree(deptList);
    System.out.println(JSON.toJSONString(depts));
}

結(jié)果打?。?/p>

[{
	"deptId": 1,
	"parentId": 0,
	"deptName": "部門(mén)0-1",
	"children": [{
		"deptId": 3,
		"parentId": 1,
		"deptName": "部門(mén)1-1",
		"children": [{
			"deptId": 7,
			"parentId": 3,
			"deptName": "部門(mén)1-1-1",
			"children": []
		}, {
			"deptId": 8,
			"parentId": 3,
			"deptName": "部門(mén)1-1-2",
			"children": []
		}]
	}, {
		"deptId": 4,
		"parentId": 1,
		"deptName": "部門(mén)1-2",
		"children": []
	}]
}, {
	"deptId": 2,
	"parentId": 0,
	"deptName": "部門(mén)0-2",
	"children": [{
		"deptId": 5,
		"parentId": 2,
		"deptName": "部門(mén)2-1",
		"children": []
	}, {
		"deptId": 6,
		"parentId": 2,
		"deptName": "部門(mén)2-2",
		"children": [{
			"deptId": 9,
			"parentId": 6,
			"deptName": "部門(mén)2-2-1",
			"children": []
		}, {
			"deptId": 10,
			"parentId": 6,
			"deptName": "部門(mén)2-2-2",
			"children": []
		}]
	}]
}]

以上就是使用Java注解構(gòu)建樹(shù)結(jié)構(gòu)工具類(lèi)的方法。使用注解可以為代碼添加更多的語(yǔ)義信息,提高代碼的可讀性和可維護(hù)性

到此這篇關(guān)于Java通過(guò)注解實(shí)現(xiàn)構(gòu)建樹(shù)結(jié)構(gòu)工具類(lèi)的文章就介紹到這了,更多相關(guān)Java構(gòu)建樹(shù)結(jié)構(gòu)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

边坝县| 墨竹工卡县| 秦安县| 桃源县| 镇江市| 岐山县| 辛集市| 漳州市| 喜德县| 彰武县| 白水县| 乌拉特后旗| 台山市| 海阳市| 崇信县| 黄平县| 博白县| 奉新县| 梧州市| 乌拉特后旗| 东兴市| 同仁县| 黄冈市| 太保市| 新乡县| 林甸县| 集安市| 涪陵区| 保德县| 潍坊市| 安康市| 周至县| 海口市| 浮梁县| 沾益县| 泉州市| 平泉县| 长子县| 荆门市| 云阳县| 裕民县|