JAVA代碼實現多級樹結構封裝對象

package microservice.fpzj.utils;

import microservice.fpzj.po.dict.FpzjXzdwArray;
import org.aspectj.weaver.ast.Test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 做者 楊柳
 * 建立時間 2017-07-05 16:54
 */
public class TreeUtils {

 //例子
    public static void main(String[] args){
        TestTree testTree = new TestTree();
        testTree.setId("1001");
        testTree.setName("濰坊市");
        testTree.setPid("1000");
        TestTree testTree1 = new TestTree();
        testTree1.setId("1002");
        testTree1.setName("青島市");
        testTree1.setPid("1000");
        TestTree testTree2 = new TestTree();
        testTree2.setId("1001001");
        testTree2.setName("高新區");
        testTree2.setPid("1001");
        TestTree testTree3 = new TestTree();
        testTree3.setId("1002001");
        testTree3.setName("四方區");
        testTree3.setPid("1002");
        TestTree testTree4 = new TestTree();
        testTree4.setId("1000");
        testTree4.setName("山東省");
        testTree4.setPid("0");
        TestTree testTree5 = new TestTree();
        testTree5.setId("1001001001");
        testTree5.setName("清池街辦");
        testTree5.setPid("1001001");
        List<TestTree> testTreeList = new ArrayList<>();
        testTreeList.add(testTree);
        testTreeList.add(testTree1);
        testTreeList.add(testTree2);
        testTreeList.add(testTree3);
        testTreeList.add(testTree4);
        testTreeList.add(testTree5);
        TreeUtils.createTree(testTreeList,testTree4,"id","pid","testTrees");
        System.out.println(testTree4); //經過上邊的createTree方法,根節點,即testTree4就是最全的最後的樹結構。
    }

    /**
     * @param list               樹數據
     * @param root               根節點
     * @param keyFieldName       關聯屬性
     * @param parentKeyFieldName 關聯父屬性
     * @param subFieldName       子節點數據
     * @param <T>                根節點
     */
    public static <T> void createTree(List<T> list, T root, String keyFieldName, String parentKeyFieldName, String subFieldName) {
        Field keyField = ReflectUtils.getField(keyFieldName, root);
        Field parentKeyField = ReflectUtils.getField(parentKeyFieldName, root);
        Field subField = ReflectUtils.getField(subFieldName, root);
        find(list, root, keyField, parentKeyField, subField);
    }

    /**
     * 根據父節點的關聯值 查找
     */
    public static <T, E> List<E> getKeys(List<T> list, T root, String keyFieldName, String parentKeyFieldName) {
        Field keyField = ReflectUtils.getField(keyFieldName, root);
        Field parentKeyField = ReflectUtils.getField(parentKeyFieldName, root);
        List<E> keys = new ArrayList<>();
        E value = ReflectUtils.getValueByGetMethod(keyField, root);
        keys.add(value);
        findKeys(list, keys, root, keyField, parentKeyField);
        return keys;
    }

    private static <T> void find(List<T> list, T parent, Field keyField, Field parentKeyField, Field subField) {
        List<T> subs = getSubs(list, parent, keyField, parentKeyField);

        if (subs != null) {
            ReflectUtils.setValueByField(subField, parent, subs);
            for (T sub : subs) {
                //遞歸找子節點
                find(list, sub, keyField, parentKeyField, subField);
            }
        }
    }

    private static <T, E> List<E> findKeys(List<T> list, List<E> keys, T parent, Field keyField, Field parentKeyField) {
        List<T> subs = getSubs(list, parent, keyField, parentKeyField);

        List<E> subKeys = getSubKeys(list, parent, keyField, parentKeyField);
        if (subs != null) {
            keys.addAll(subKeys);
            for (T sub : subs) {
                //遞歸找子節點
                findKeys(list, keys, sub, keyField, parentKeyField);
            }
        }
        return keys;
    }


    private static <T> List<T> getSubs(List<T> list, T parent, Field keyField, Field parentKeyField) {
        List<T> subs = null;
        for (T t : list) {
            Object keyFieldValue = ReflectUtils.getValueByField(keyField, parent);
            Object parentFieldValue = ReflectUtils.getValueByField(parentKeyField, t);
            if (keyFieldValue.equals(parentFieldValue)) {
                if (subs == null) {
                    subs = new ArrayList<>();
                }
                subs.add(t);
            }
        }
        return subs;
    }


    private static <T, E> List<E> getSubKeys(List<T> list, T parent, Field keyField, Field parentKeyField) {
        List<E> subs = null;
        for (T t : list) {
            Object keyFieldValue = ReflectUtils.getValueByField(keyField, parent); //父節點key
            Object parentFieldValue = ReflectUtils.getValueByField(parentKeyField, t); //根結點關聯的key
            if (keyFieldValue.equals(parentFieldValue)) { //關聯字段相等
                if (subs == null) {
                    subs = new ArrayList<>();
                }
                //取子節點key
                Object key = ReflectUtils.getValueByField(keyField, t);
                subs.add((E) key);
            }
        }
        return subs;
    }
   
}
class TestTree{
    private String id;
    private String name;
    private String pid;
    private List<TestTree> testTrees;

    public List<TestTree> getTestTrees() {
        return testTrees;
    }

    public void setTestTrees(List<TestTree> testTrees) {
        this.testTrees = testTrees;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }
}
package microservice.fpzj.utils;


import org.apache.commons.lang3.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by 楊柳 on 2016/8/5 0005.
 * email:yangliu@buestc.com
 * tel:18523437817
 */
public class ReflectUtils {

    /**
     * 根據屬性名獲取屬性
     */
    public static Field getField(String fieldName, Class<?> clazz) {
        Class<?> old = clazz;
        Field field = null;
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                if (field != null) {
                    break;
                }
            } catch (Exception e) {
            }
        }
        if (field == null) {
            throw new NullPointerException(old + "沒有" + fieldName + "屬性");
        }
        return field;
    }

    /**
     * 獲取目標類的屬性
     */
    public static Field getField(String fieldName, String className) {
        try {
            return getField(fieldName, Class.forName(className));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 獲取目標對象的屬性
     */
    public static Field getField(String fieldName, Object object) {
        return getField(fieldName, object.getClass());
    }


    /**
     * 獲取當前類的屬性 包括父類
     */
    public static List<Field> getFields(Class<?> clazz, Class<?> stopClass) {
        try {
            List<Field> fieldList = new ArrayList<>();
            while (clazz != null && clazz != stopClass) {//當父類爲null的時候說明到達了最上層的父類(Object類).
                fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
                clazz = clazz.getSuperclass(); //獲得父類,而後賦給本身
            }
            return fieldList;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }




    /**
     * 獲取當前類的屬性 包括父類
     */
    @Deprecated
    public static List<Field> getFields(Class<?> clazz) {
        return getFields(clazz, Object.class);
    }

    private static List<Class<?>> getSuperClasses(Class<?> clazz, Class<?> stopClass) {
        List<Class<?>> classes = new ArrayList<>();
        while (clazz != null && clazz != stopClass) {//當父類爲null的時候說明到達了最上層的父類(Object類).
            classes.add(clazz);
            clazz = clazz.getSuperclass(); //獲得父類,而後賦給本身
        }
        return classes;
    }


    /**
     * 經過屬性賦值
     */
    public static void setValueByField(String fieldName, Object object, Object value) {
        Field field = getField(fieldName, object.getClass());
        setValueByField(field, object, value);
    }

    /**
     * 經過屬性賦值
     */
    public static void setValueByField(Field field, Object object, Object value) {
        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
                field.set(object, value);
                field.setAccessible(false);
            } else {
                field.set(object, value);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    /**
     * 獲取屬性的值
     */
    public static <T> T getValueByField(String fieldName, Object object) {
        Field field = getField(fieldName, object.getClass());
        return getValueByField(field, object);
    }

    /**
     * 獲取屬性的值
     */
    public static <T> T getValueByField(Field field, Object object) {
        try {
            Object value;
            if (!field.isAccessible()) {
                field.setAccessible(true);
                value = field.get(object);
                field.setAccessible(false);
            } else {
                value = field.get(object);
            }
            return (T) value;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 經過set方法賦值
     */
    public static void setValueBySetMethod(String fieldName, Object object, Object value) {
        if (object == null) {
            throw new RuntimeException("實例對象不能爲空");
        }
        if (value == null) {
            return;
        }
        try {
            String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method setMethod = getMethod(setMethodName, object.getClass(), value.getClass());
            setMethod.invoke(object, value);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 經過set方法賦值
     */
    public static void setValueBySetMethod(Field field, Object object, Object value) {
        if (object == null) {
            throw new RuntimeException("實例對象不能爲空");
        }
        if (value == null) {
            return;
        }
        setValueBySetMethod(field.getName(), object, value);
    }

    /**
     * 經過get方法取值
     */
    public static <T> T getValueByGetMethod(String fieldName, Object object) {
        try {
            if (StringUtils.isNotBlank(fieldName)) {
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method getMethod = getMethod(getMethodName, object.getClass());
                return (T) getMethod.invoke(object);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 經過get方法取值
     */
    public static <T> T getValueByGetMethod(Field field, Object object) {
        return getValueByGetMethod(field.getName(), object);
    }


    /**
     * 獲取某個類的某個方法(當前類和父類)
     */
    public static Method getMethod(String methodName, Class<?> clazz) {
        Method method = null;
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName);
                break;
            } catch (Exception e) {
            }
        }
        if (method == null) {
            throw new NullPointerException("沒有" + methodName + "方法");
        }
        return method;
    }

    /**
     * 獲取get方法
     *
     * @param fieldName 屬性名
     * @return
     */
    public static String getMethodName(String fieldName) {
        String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        return methodName;
    }

    /**
     * 獲取某個類的某個方法(當前類和父類) 帶一個參數
     */
    public static Method getMethod(String methodName, Class<?> clazz, Class<?> paramType) {
        Method method = null;
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, paramType);
                if (method != null) {
                    return method;
                }
            } catch (Exception e) {
            }
        }
        if (method == null) {
            throw new NullPointerException(clazz + "沒有" + methodName + "方法");
        }
        return method;
    }

    /**
     * 獲取某個類的某個方法(當前類和父類)
     */
    public static Method getMethod(String methodName, Object obj) {
        return getMethod(methodName, obj.getClass());
    }

    /**
     * 獲取某個類的某個方法(當前類和父類) 一個參數
     */
    public static Method getMethod(String methodName, Object obj, Class<?> paramType) {
        return getMethod(methodName, obj.getClass(), paramType);
    }

    /**
     * 獲取某個類的某個方法(當前類和父類)
     */
    public static Method getMethod(String methodName, String clazz) {
        try {
            return getMethod(methodName, Class.forName(clazz));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    /**
     * 獲取某個類的某個方法(當前類和父類) 一個參數
     */
    public static Method getMethod(String methodName, String clazz, Class<?> paramType) {
        try {
            return getMethod(methodName, Class.forName(clazz), paramType);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    /**
     * 獲取方法上的註解
     */
    public static Annotation getMethodAnnotation(Method method, Class targetAnnotationClass) {
        Annotation methodAnnotation = method.getAnnotation(targetAnnotationClass);
        return methodAnnotation;
    }

    /**
     * 獲取屬性上的註解
     */
    public static Annotation getFieldAnnotation(Field field, Class targetAnnotationClass) {
        Annotation methodAnnotation = field.getAnnotation(targetAnnotationClass);
        return methodAnnotation;
    }

    /**
     * 獲取類上的註解
     *
     * @param targetAnnotationClass 目標註解
     * @param targetObjcetClass     目標類
     * @return 目標註解實例
     */
    public static Annotation getClassAnnotation(Class targetAnnotationClass, Class<?> targetObjcetClass) {
        Annotation methodAnnotation = targetObjcetClass.getAnnotation(targetAnnotationClass);
        return methodAnnotation;
    }

    /**
     * 獲取類上的註解
     *
     * @return 目標註解實例
     */
    public static Annotation getClassAnnotation(Class targetAnnotationClass, Object obj) {
        return getClassAnnotation(targetAnnotationClass, obj.getClass());
    }

    /**
     * 獲取類上的註解
     *
     * @return 目標註解實例
     */
    public static Annotation getClassAnnotation(Class targetAnnotationClass, String clazz) {
        try {
            return getClassAnnotation(targetAnnotationClass, Class.forName(clazz));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    /**
     * 獲取註解某個屬性的值
     *
     * @param methodName 屬性名
     * @param annotation 目標註解
     * @param <T>        返回類型
     * @throws Exception
     */
    public static <T> T getAnnotationValue(String methodName, Annotation annotation) {
        try {
            Method method = annotation.annotationType().getMethod(methodName);
            Object object = method.invoke(annotation);
            return (T) object;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    /**
     * 獲取某個類的某個方法上的某個註解的屬性
     *
     * @param methodName            註解屬性的名字
     * @param targetAnnotationClass 目標註解
     * @param targetObjecMethodName 目標類的方法
     * @param targetObjectClass     目標類
     * @param <T>                   返回值類型
     */
    public static <T> T getMethodAnnotationValue(String methodName, Class targetAnnotationClass, String targetObjecMethodName, Class targetObjectClass) {
        Method method = getMethod(targetObjecMethodName, targetObjectClass);
        Annotation annotation = getMethodAnnotation(method, targetAnnotationClass);
        return getAnnotationValue(methodName, annotation);
    }

    /**
     * @param methodName            註解屬性名
     * @param targetAnnotationClass 目標註解
     * @param targetObjecFieldName  目標屬性名字
     * @param targetObjectClass     目標類
     * @param <T>                   返回值類型
     */
    public static <T> T getFieldAnnotationValue(String methodName, Class targetAnnotationClass, String targetObjecFieldName, Class targetObjectClass) {
        Field field = getField(targetObjecFieldName, targetObjectClass);
        Annotation annotation = getFieldAnnotation(field, targetAnnotationClass);
        return getAnnotationValue(methodName, annotation);
    }

    /**
     * 判斷 clazz是不是target的子類型或者相等
     */
    public static boolean isSubClassOrEquesClass(Class<?> clazz, Class<?> target) {
        if (clazz == target) {
            return true;
        }
        while (clazz != Object.class) {
            if (clazz == target) {
                return true;
            }
            clazz = clazz.getSuperclass();
        }
        return false;
    }

}
相關文章
相關標籤/搜索