第一次在项目中用到反射解决问题。简简单单记录一下hh。

应用背景: 接了一个数据同步的需求,公司有订阅Mysql binlog的组件(应该是canal),然后会将数据库表中的变化通过MQ的形式发送消息,我们只要去消费消息就可以实时去同步一些东西,MQ发送的数据结构是一串json,类似与这样

 "filed_name":	{"v":"test"}

因为要对这些数据进行实时插库或者修改,这种格式也没法直接转成实体类,每一个字段都去set属性太累!!

经过师傅指点下提示我用反射写个工具类,然后就有了下面这段代码hh。

	Method[] methods = clazz.getMethods();
     for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
         JSONObject jsonObject2 = JSONObject.parseObject(JSONObject.toJSONString(entry.getValue()));
         String filed = underlineToCamel(entry.getKey());
         String camelFiled = filed.substring(0, 1).toUpperCase() + filed.substring(1);
         Field field = clazz.getDeclaredField(filed);

         field.setAccessible(true);
         Class<?> type = field.getType();
         Object v = jsonObject2.getObject("v", type);
         String methodName = "set" + camelFiled;

         for (Method m : methods) {
             if (m.getName().equals(methodName)) {
                 m.invoke(o, v);
                 break;
             }
         }
     }

没啥高超的技术,就是通过反射获取实体类的set方法以及字段属性,再去动态的设置hh,果然只有懒的时候才会去想一些工具类减少操作!