Java通過注解實現(xiàn)構(gòu)建樹結(jié)構(gòu)工具類
前言
在Java中,注解是一種元數(shù)據(jù),可以提供有關(guān)代碼的附加信息。通過使用注解,可以在代碼中添加配置信息、驗證條件、文檔和其他信息,這使得代碼更易于理解和維護。在本文中,我將介紹如何使用Java注解構(gòu)建樹結(jié)構(gòu)工具類。
話不多說,現(xiàn)在開搞======================>
枚舉類
標(biāo)識字段的數(shù)據(jù)類型
public enum DataType {
/** long */
LONG,
/** string */
STRING,
/** LIST */
LIST,
}
注解
標(biāo)識字段為主鍵
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PrimaryKey {
/** 字段數(shù)據(jù)類型默認(rèn)為 long */
DataType dataType() default DataType.LONG;
}
標(biāo)識字段為父id
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ParentKey {
/** 字段數(shù)據(jù)類型默認(rèn)為 long */
DataType dataType() default DataType.LONG;
}
標(biāo)識字段為子集
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ChildrenKey {
/** 字段數(shù)據(jù)類型默認(rèn)為 List */
DataType dataType() default DataType.LIST;
}
獲取注解標(biāo)識的字段值
public class AnnotationUtil {
/**
* 獲取注解 annotation 標(biāo)識的字段值
* @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)建樹結(jié)構(gòu)工具類
public class TreeUtils {
private static final Logger log = LoggerFactory.getLogger(TreeUtils.class);
/**
* 構(gòu)建前端所需要樹結(jié)構(gòu),主鍵為 Long 時
* @param tList 數(shù)據(jù)集
* @return java.util.List<T> 樹結(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) {
// 如果是頂級節(jié)點, 遍歷該父節(jié)點的所有子節(jié)點
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("樹結(jié)構(gòu)轉(zhuǎn)換失?。簕}", e.getMessage());
return tList;
}
}
/**
* 構(gòu)建前端所需要樹結(jié)構(gòu),主鍵為 String 時
* @param tList 數(shù)據(jù)集
* @return java.util.List<T> 樹結(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) {
// 如果是頂級節(jié)點, 遍歷該父節(jié)點的所有子節(jié)點
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("樹結(jié)構(gòu)轉(zhuǎn)換失?。簕}", e.getMessage());
return tList;
}
}
/**
* 遞歸設(shè)置子集數(shù)據(jù),主鍵為 Long 時
* @param list 數(shù)據(jù)集合
* @param o 對象
*/
private static <T> void recursionLong(List<T> list, Object o) throws IllegalAccessException {
// 得到子節(jié)點列表
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 時
* @param list 數(shù)據(jù)集合
* @param o 對象
*/
private static <T> void recursionString(List<T> list, Object o) throws IllegalAccessException {
// 得到子節(jié)點列表
List<T> childList = getStringChildList(list, o);
invokeChildrenList(o, childList);
for (Object oChild : childList) {
if (getStringChildList(list, oChild).size() > 0) {
recursionString(list, oChild);
}
}
}
/**
* 得到子節(jié)點列表,主鍵為 Long 時
* @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é)點列表,主鍵為 String 時
* @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;
}
/**
* 通過反射設(shè)置子集數(shù)據(jù)
* @param o 對象
* @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;
}
}
}
}
測試一下
部門 dept 類
// 此處使用lombok減少代碼
@Data
public class Dept implements Serializable {
private static final long serialVersionUID = -1L;
/**
* 部門ID
* 如果數(shù)據(jù)類型為字符串,則 @PrimaryKey(dataType = DataType.STRING)
*/
@PrimaryKey
private Long deptId;
/**
* 父部門ID
* 如果數(shù)據(jù)類型為字符串,則 @ParentKey(dataType = DataType.STRING)
*/
@ParentKey
private Long parentId;
/** 部門名稱 */
private String deptName;
/** 子部門 */
@ChildrenKey
private List<Dept> children = new ArrayList<>();
/** 加一個有參構(gòu)造,方便測試 */
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, "部門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<Dept> depts = TreeUtils.buildLongTree(deptList);
System.out.println(JSON.toJSONString(depts));
}
結(jié)果打印:
[{
"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": []
}]
}]
}]以上就是使用Java注解構(gòu)建樹結(jié)構(gòu)工具類的方法。使用注解可以為代碼添加更多的語義信息,提高代碼的可讀性和可維護性
到此這篇關(guān)于Java通過注解實現(xiàn)構(gòu)建樹結(jié)構(gòu)工具類的文章就介紹到這了,更多相關(guān)Java構(gòu)建樹結(jié)構(gòu)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springMVC前臺傳數(shù)組類型,后臺用list類型接收實例代碼
這篇文章主要介紹了springMVC前臺傳數(shù)組類型,后臺用list類型接收實例代碼,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12
springboot整合規(guī)則引擎(liteflow)使用方式
這篇文章主要介紹了springboot整合規(guī)則引擎(liteflow)使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-07-07
Java 如何將前端傳來的數(shù)字轉(zhuǎn)化為日期
這篇文章主要介紹了Java 如何將前端傳來的數(shù)字轉(zhuǎn)化為日期,本文通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2023-06-06
解決Spring session(redis存儲方式)監(jiān)聽導(dǎo)致創(chuàng)建大量redisMessageListenerConta
這篇文章主要介紹了解決Spring session(redis存儲方式)監(jiān)聽導(dǎo)致創(chuàng)建大量redisMessageListenerContailner-X線程問題,需要的朋友可以參考下2018-08-08
Springboot實現(xiàn)通用Auth認(rèn)證的幾種方式
本文主要介紹了Springboot實現(xiàn)通用Auth認(rèn)證的幾種方式,主要介紹了4種方式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07
Spring?Boot源碼實現(xiàn)StopWatch優(yōu)雅統(tǒng)計耗時
這篇文章主要為大家介紹了Spring?Boot源碼實現(xiàn)StopWatch優(yōu)雅統(tǒng)計耗時,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
Java使用Maven BOM統(tǒng)一管理版本號的實現(xiàn)
這篇文章主要介紹了Java使用Maven BOM統(tǒng)一管理版本號的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
解決jhipster修改jdl生成的實體類報錯:liquibase.exception.ValidationFailed
這篇文章主要介紹了解決jhipster修改jdl生成的實體類報錯:liquibase.exception.ValidationFailedException: Validation Failed問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

