最近项目上和其他团队的同学进行对接,发现他们对String类型的数据为"" 的时候处理不符合预期,这种为""的数据只能传null的时候,他们才能正确处理
这个要求~~~ 没事 安排
功能实现:
private static void changeParam(Object obj, Object expectValue,Function<Object, Boolean> function) throws Exception { Class<?> clazz = obj.getClass(); BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor p : pds) { Method readMethod = p.getReadMethod(); Method writeMethod = p.getWriteMethod(); if (null == writeMethod) { continue; } Object result = readMethod.invoke(obj); if (function.apply(result)) { result = expectValue; writeMethod.invoke(obj, result); } } }
测试验证:
public static void main(String[] args) throws Exception { Person person = new Person(); person.setName("zhangsan"); person.setAge("18"); person.setWork("java"); person.setAddress(""); System.out.println(person); changeParam(person, null , p -> { if (p != null && p instanceof String && StringUtils.isBlank((String) p)) { return true; } return false; }); System.out.println(person); }
结果:
写代码就得一把梭 下班走人