java反射之-Javabean与Map的互转
1.BeanUntils工具类的准备
/** * @ClassName: BeanUtils * @Description: * @Author: songwp * @Date: 9:02 2022/5/19 **/ public class BeanUtils { /** * 将javaBean转换成Map * @param bean * @return * @throws Exception */ public static Map<String,Object> beanToMap(Object bean) throws Exception { Map<String,Object> map = new HashMap<>(); BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { String name = pd.getName(); Object value = pd.getReadMethod().invoke(bean); map.put(name,value); } return map; } /** * 将Map转成javaBean * @param map * @param beanType * @param <T> * @return * @throws Exception */ public static <T> T mapToBean(Map<String,Object> map,Class<T> beanType) throws Exception { // 创建javaBean对象 Object obj = beanType.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(beanType, Object.class); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { // 从Map中获取属性同名的key值 Object value = map.get(pd.getName()); // 调用setter方法设置属性值 pd.getWriteMethod().invoke(obj,value); } return (T)obj; } }
2.方法测试调用
注意:User 和 Person实体需要自己创建(person的属性和map中的key要有对应)
/** * @ClassName: Test9 * @Description: * @Author: songwp * @Date: 9:23 2022/5/19 **/ public class Test9 { public static void main(String[] args) throws Exception { //1.map转JavaBean Map<String,Object> map = new HashMap<>(); map.put("name","李四"); map.put("age","28"); map.put("address","陕西西安"); Object user1 = BeanUtils.mapToBean(map, Person.class); System.out.println(user1); System.out.println("================================================================"); //2. javabean转map User user = new User(); user.setId("10001"); user.setStatus(0); user.setPhone("18740458584"); user.setNickname("张三"); Map<String, Object> map1 = BeanUtils.beanToMap(user); System.out.println(map1); } }
3.结果如下:
----------------------------------------------------------------------------- Person(name=李四, age=28, address=陕西西安) ================================================================ {birthday=null, password=null, gender=null, phone=18740458584, nickname=张三, remark=null, id=10001, age=null, status=0, username=null} -----------------------------------------------------------------------------
古今成大事者,不唯有超世之才,必有坚韧不拔之志!