Java 通过属性名称读取或者设置实体的属性值

原因

项目实战中有这个需求,数据库中配置对应的实体和属性名称,在代码中通过属性名称获取实体的对应的属性值。

解决方案

工具类,下面这个工具是辅助获取属性值

import com.alibaba.fastjson.JSONObject;
public class StringUtil {
    /**
     * 对象转成json字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        return JSONObject.toJSONString(obj);
    }

    /**
     * 对象转成JSONObject
     *
     * @param obj
     * @return
     */
    public static JSONObject toJsonObject(Object obj) {
        return JSONObject.parseObject(toJson(obj));
    }

    /**
     * 获取对象的指定字段的值
     *
     * @param obj
     * @param propName
     * @return
     */
    public static String getPropValue(Object obj, String propName){
        String propValue = StringConst.EMPTY;
        try {
            if(null!=obj) {
                JSONObject jsonObject = toJsonObject(obj);
                if (!StringUtil.isEmptyOrNull(propName)) {
                    propValue = jsonObject.getString(propName);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return propValue;
    }
}

下面这个是提供给接口使用的读取设置属性值的工具类

/**
 * @Description: 读取指定实体类的指定属性字段值
 */
public class TableUtil {
    /**
     * 通过propName传进来的值,判断从哪个表取值
     *
     * @param obj        当前使用的实体
     * @param propName   表名.列名;表名.列名
     * @return
     */
    public String getValue(Object obj, String propName) {
        StringBuilder stringBuilder = new StringBuilder(StringConst.EMPTY);
        List<String> props = Arrays.stream(StringUtil.ifEmptyOrNullReturnValue(propName).split(";")).collect(Collectors.toList());
        for (String prop : props) {
            String temp = null;
            List<String> tableNames = Arrays.stream(StringUtil.ifEmptyOrNullReturnValue(prop).split("\.")).collect(Collectors.toList());
            // 表名.列名,数据库中配置的是实体名称+属性名称
            if (tableNames.size() > 1) {
                // 表名
                String tableName = tableNames.get(0);
                // 列名
                String colName = tableNames.get(1);
                if ("special".equalsIgnoreCase(tableName)) {// 如果需要对一些实体进行特殊处理,比如说某些实体从缓存读取,或者某个实体中的属性值需要特殊处理,就可以在下面增加特殊处理逻辑
                    temp = StringUtil.getPropValue(specialModel, colName);
                } else {
                    temp = StringUtil.getPropValue(obj, colName);
                }
            } else if (tableNames.size() > 0) {// 数据库中只配置了属性名称,说明只有某个实体才会用到该记录,到时候获取属性值的时候记得把obj传进来
                // 列名
                String colName = tableNames.get(0);
                if (colName.contains("?")) {//特殊处理数据库中配置的三目运算符
                    // 如:sheathProtector=="有"?0:1
                    String tempColName = colName.split("\?")[0].split("==")[0].trim();
                    String tempColValue = colName.split("\?")[0].split("==")[1].replace(""", "").replace("'", "").trim();
                    String tempValue = StringUtil.getPropValue(obj, tempColName);
                    if (tempValue.equals(tempColValue)) {
                        temp = colName.split("\?")[1].split(":")[0];
                    } else {
                        temp = colName.split("\?")[1].split(":")[1];
                    }
                } else {
                    temp = StringUtil.getPropValue(obj, colName);
                }
            }
        }
        String result = stringBuilder.toString();
        return result;
    }

    /**
     * 为实体赋值
     *
     * @param obj
     * @param propName
     * @param value
     * @return
     */
    public Object setValue(Object obj, String propName, String value) {
        try {
            Field f = obj.getClass().getDeclaredField(propName);
            f.setAccessible(true);
            f.set(obj, value);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }
    
}

使用

TableUtil tableUtil;
public void test(){
      Person p = new Person();
      String age = tableUtile.getValue(p,"age");// 读取属性值
      tableUtil.setValue(p,"age",23);// 设置属性值
}
原文地址:https://www.cnblogs.com/dawenyang/p/15261080.html