反射

使用spring的ReflectionUtils写的工具类

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 *  Author: tanglj 
 *  Created: 16:53
 */
public class ReflectionUtil {
    /**
     * 通过反射获取修改某个field的值
     *
     * @param target
     * @param fieldName
     * @return
     */
    public static void setFieldValue(Object target, String fieldName, Object fieldValue) {
        Class targetClass = target.getClass();
        Field field = ReflectionUtils.findField(targetClass, fieldName);
        if (field != null) {
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, target, fieldValue);
        }
    }

    /**
     * 通过反射获取某个对象的field的值
     *
     * @param target
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object target, String fieldName) {
        Class targetClass = target.getClass();
        Field field = ReflectionUtils.findField(targetClass, fieldName);
        if (field != null) {
            ReflectionUtils.makeAccessible(field);
            return ReflectionUtils.getField(field, target);
        }
        return null;
    }

    public static Map<String, Object> objectToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(obj);
                map.put(fieldName, value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
posted @ 2022-05-12 15:25  原来是晴天啊  阅读(42)  评论(0编辑  收藏  举报