Java 根据反射机制操作实体字段FieldUtil

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

/**
 * TODO
 */
public class FiledUtil {

    /*
    根据bean获取所有字段信息
     */
    public List<Field> getFieldList(String bean) {
        List<Field> fieldList = new ArrayList<>();
        try {
            Class<?> clz = Class.forName(bean);
            Field[] strsSub = clz.getDeclaredFields();
            Class<?> clzSuper = Class.forName(bean).getSuperclass();
            for (Field filed : strsSub) {
                fieldList.add(filed);
            }
            if (null != clzSuper) {
                Field[] strsSuper = clzSuper.getDeclaredFields();
                for (Field filed : strsSuper) {
                    fieldList.add(filed);
                }
            }
        } catch (Exception e) {
            ExceptUtils.printStackTrace(e);
        }
        return fieldList;
    }

    /*
     * 根据属性名获取属性值
     */
    public Object getFieldValueByName(String fieldName, Object obj) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = obj.getClass().getMethod(getter, new Class[] {});
            method.setAccessible(true);
            Object value = method.invoke(obj, new Object[] {});
            return value;
        } catch (Exception e) {
            ExceptUtils.printStackTrace(e);
        }
        return null;
    }

    /*
    根据字段设置对象对应字段值
     */
    public void setObjFieldValueByName(Object obj, String fieldName, Object fieldValue) {
        String bean = obj.getClass().getName();
        List<Field> fieldList = getFieldList(bean);
        for (Field field : fieldList) {
            if (!fieldName.equals(field.getName())) {
                continue;
            }
            field.setAccessible(true);
            try {
                field.set(obj, fieldValue);
            } catch (IllegalAccessException e) {
                ExceptUtils.printStackTrace(e);
            }
        }
    }
}

  

posted @ 2020-07-30 11:16  ヤBig、Bossづ  阅读(438)  评论(0编辑  收藏  举报