All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zyy.common.util.ReflexUtil Maven / Gradle / Ivy

package com.zyy.common.util;

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

/**
 * 反射工具类
 *
 * @author : li.yang
 * @version :
 * date : 2019/12/11 14:06
 */
public class ReflexUtil {
    /**
     * 获取字段列包括父类
     *
     * @param model 实体类
     * @param param 需要获取的字段名
     * @param    泛型
     * @return Field实体
     */
    public static  Field getFiled(T model, String param) {
        Class clazz = model.getClass();
        return getFiled(clazz, param);
    }

    /**
     * 获取字段列包括父类
     *
     * @param clazz 反射
     * @param param 需要获取的字段名
     * @return Field实体
     */
    public static Field getFiled(Class clazz, String param) {
        Field field = null;
        while (clazz != null && clazz != Object.class) {
            try {
                field = clazz.getDeclaredField(param);
                break;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return field;
    }

    /**
     * 获取方法包括父类
     *
     * @param clazz 反射
     * @param param 需要获取的字段名
     * @return Field实体
     */
    public static Method getMethod(Class clazz, String param, Class... paramType) {
        Method method = null;
        while (clazz != null && clazz != Object.class) {
            try {
                method = clazz.getDeclaredMethod(param, paramType);
                break;
            } catch (NoSuchMethodException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return method;
    }

    /**
     * 获取字段列包括父类
     *
     * @param model 实体类
     * @param    泛型
     * @return 所有字段Field
     */
    public static  List getFields(T model) {
        Class clazz = model.getClass();
        List fields = new ArrayList<>();
        while (clazz != null && clazz != Object.class) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy