原因
項目實戰中有這個需求,數據庫中配置對應的實體和屬性名稱,在代碼中通過屬性名稱獲取實體的對應的屬性值。
解決方案
工具類,下面這個工具是輔助獲取屬性值
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);// 設置屬性值 }