在做解析XML时候经常要将数据转换成为对象,手动设置对象每个属性的值太麻烦了,而且属性太多时经常漏掉,所以在不十分在意效率的情况下偷懒一下
/**
* 将对象转换为map * @param rgxBean * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ private Map<String,Object> convertMap(Object obj) throws IllegalArgumentException, IllegalAccessException{ Map<String,Object> map=new HashMap<String,Object>(); Field[] fields=obj.getClass().getDeclaredFields(); for(Field field:fields){field.setAccessible(true);
map.put(field.getName(), field.get(rgxBean));field.setAccessible(false);
} return map; } /** * 将Map转换成为对象 * @param map * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ private Object convertObj(Map<String,Object> map) throws IllegalArgumentException, IllegalAccessException{ Object obj=new Object(); Field[] fields=obj.getClass().getDeclaredFields(); for(Field field:fields){ field.setAccessible(true); field.set(obj, map.get(field.getName())); field.setAccessible(false); } return obj; }