通过properties和反射优化数据对接时候属性名不一样的问题
数据对接时候,传过来的数据和自己数据库表字段的数据不一致,一般if去转换处理,但是当字段特别多时候,比如一些软属性,有几百个,分别对应到自己数据库不同表不同字段上,这个时候if这样转换代码就特别多,而且有的属性修改时候是个很大的工作量。
这个时候可以这样处理:
- 使用properties配置文件把传过来的属性和自己数据库字段属性对应上
- 把properties文件内容返回成map,在数据转换时候通过map.get(key)方式获取自己数据库字段,把自己数据库字段和传过来的值绑定上放到新的map里面
- 通过反射去set不同的属性值
代码如下:
test.properties
userInfo.name=userName
userInfo.xl=education
userInfo.nl=age
userInfo.xb=sex
ReflectUtil.java
public class ReflectUtil {/*** 获取参数类型* @param t* @param str* @param <T>* @return*/public static <T> Class<?>[] getParameterTypes(T t, String str){Class<?>[] parameterTypes;Class clazz = t.getClass();Method[] declaredMethods = clazz.getDeclaredMethods();for (Method declaredMethod : declaredMethods) {if(declaredMethod.getName().equals(str)){parameterTypes = declaredMethod.getParameterTypes();return parameterTypes;}}return null;}
}
PropUtil.java
public class PropUtil {/*** 通过反射把map对象的内容set到对象里面并返回对象* @param t* @param params* @param <T>* @return* @throws Exception*/public static <T> T getObj(T t, Map<String, Object> params) {Object obj = null;Class clazz = t.getClass();Iterator<String> iterator = params.keySet().iterator();try {obj = clazz.newInstance();BeanUtils.copyProperties(t, obj);while (iterator.hasNext()) {String key = iterator.next();//拼接set方法名String methodName = "set" + StringUtils.capitalize(key);Method method = clazz.getMethod(methodName, ReflectUtil.getParameterTypes(t,methodName));method.invoke(obj,params.get(key));}}catch (Exception e){e.printStackTrace();}return (T) obj;}/*** 读取配置文件内容返回Map* @param startWith* @return*/public static Map<String, Object> getPropMap(String startWith){Properties properties = new Properties();Map<String,Object> map = new HashMap<>();try {properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("test.properties"));} catch (IOException e) {e.printStackTrace();}Set<Map.Entry<Object, Object>> entries = properties.entrySet();for (Map.Entry<Object, Object> entry : entries) {String keyName = (String) entry.getKey();if(StringUtils.isBlank(startWith)){map.put(keyName,entry.getValue());}else {if (startWith.equals(keyName)) {map.put(keyName.split(".")[1],entry.getValue());}}}return map;}public static void main(String[] args) {UserInfo userInfo = new UserInfo();userInfo.setSl("2年");//业务处理:根据properties文件把key对应的值,转换成map(key是property的value值,value是具体属性值)Map<String,Object> params = new HashMap<>();params.put("userName","张三");params.put("education","本科");params.put("age",25);params.put("sex","男");UserInfo obj = getObj(userInfo, params);System.out.println(obj);}
}
main方法执行结果:
UserInfo(id=null, userName=张三, education=本科, age=25, sex=男, sl=2年)