反射工具类

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public final class ReflectUtil {
    private ReflectUtil() {
    }

    /**
     * 获取SET方法
     *
     * @param fieldName
     * @param cls
     * @return
     */
    public static Method getSetter(String fieldName, Class<?> cls) {
        for (Method method : cls.getMethods()) {
            if (method.getName().equalsIgnoreCase("set".concat(fieldName)) && method.getParameterTypes().length == 0) {
                return method;
            }
        }
        return null;
    }

    /**
     * 获取GET方法
     *
     * @param fieldName
     * @param cls
     * @return
     */
    public static Method getGetter(String fieldName, Class<?> cls) {
        for (Method method : cls.getMethods()) {
            if (method.getName().equalsIgnoreCase("get".concat(fieldName)) && method.getParameterTypes().length == 0) {
                return method;
            }
        }
        return null;
    }

    /**
     * 给对象某属性赋值
     *
     * @param fieldName
     * @param obj
     * @return
     * @throws ReflectiveOperationException
     */
    public static Object setValueBySetter(String fieldName, Object obj) throws ReflectiveOperationException {
        Method setter = getSetter(fieldName, obj.getClass());
        if (setter == null) {
            throw new ReflectiveOperationException("没有set方法");
        }

        return setter.invoke(obj);
    }

    /**
     * 获取某属性的值
     *
     * @param fieldName
     * @param obj
     * @return
     * @throws ReflectiveOperationException
     */
    public static Object getValueByGetter(String fieldName, Object obj) throws ReflectiveOperationException {
        Method getter = getGetter(fieldName, obj.getClass());
        if (getter != null) {
            return getter.invoke(obj);
        }

        return null;
    }

    /**
     * 获取字段对应值,并转为String类型,空值返回空字符串
     *
     * @param fieldName
     * @param obj
     * @return
     * @throws ReflectiveOperationException
     */
    public static String getStringValue(String fieldName, Object obj) throws ReflectiveOperationException {
        Object objectValue = getValueByGetter(fieldName, obj);
        if (objectValue == null) {
            return "";
        }
        String result = objectValue.toString();
        //如果类型为BigDecimal,去掉末尾的0
        if (objectValue instanceof BigDecimal) {
            BigDecimal value = (BigDecimal) objectValue;
            value = value.stripTrailingZeros();
            result = value.toPlainString();
        } else if (objectValue instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            result = sdf.format((Date) objectValue).replace(" 00:00:00", "");
        }
        return result.trim();
    }

    /**
     * 对象是否存在某属性
     *
     * @param fieldName
     * @param cls
     * @return
     */
    public static boolean fieldExist(String fieldName, Class<?> cls) {
        return getFieldByName(fieldName, cls) != null;
    }

    /**
     * 通过对象.class获取所有Fields,包括父类
     *
     * @param cls
     * @return
     */
    public static List<Field> listFields(Class<?> cls) {
        Field[] fs = cls.getDeclaredFields();
        List<Field> fields = new ArrayList<>(Arrays.asList(fs));
        if (cls.getSuperclass() != null) {
            fields.addAll(listFields(cls.getSuperclass()));
        }
        return fields;
    }

    /**
     * 通过属性名获取Field对象
     *
     * @param fieldName
     * @param cls
     * @return
     */
    public static Field getFieldByName(String fieldName, Class<?> cls) {
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }

        if (cls.getSuperclass() != null) {
            return getFieldByName(fieldName, cls.getSuperclass());
        }

        return null;
    }
}

 

posted @   残城碎梦  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2022-11-25 说说Spring如何加载注册BeanDefinition
点击右上角即可分享
微信分享提示