有些业务场景需要对javaBean对象的每个属性转换为key-value的映射结构,避免出现大批量的setter.操作,就想到了用反射来进行处理,列如: @Component public class Bean2MapUtil { final int MAPSIZE = 256; public <T> Map<String,Object> transferBean2Map(T paramDTO,String... ignoreProperties) { if(paramDTO == null) { throw new SandBeachException(SandBeachCodeEnum.BEAN_CONVERT_ERROR); } try { Map<String,Object> map = new HashMap<>(MAPSIZE); Class<?> dtoClazz = paramDTO.getClass(); // 内省+反射获取对象的setter/getter BeanInfo beanInfo = Introspector.getBeanInfo(dtoClazz); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor pd : pds) { String fieldName = pd.getName(); if(StringUtils.containsIgnoreCase(fieldName, "class")) { continue; } // 忽略字段 if(ignoreList != null && ignoreList.contains(fieldName)) { continue; } Method readMethod = pd.getReadMethod(); if(readMethod != null) { readMethod.setAccessible(true); Object value = readMethod.invoke(paramDTO); // 必转换字段 map.put(fieldName, value); } } return map; } catch (Exception e) { throw new SandBeachException(SandBeachCodeEnum.BEAN_CONVERT_ERROR); } } } |
|
来自: 小清风的doc > 《springframework》