Java对象和Map互相转换的6种方式

时间:2025-02-16 10:48:23
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IntrospectionException, InvocationTargetException { Map<String, Object> map = new HashMap(); map.put("id", 1L); map.put("name", "三省同学"); //map转java对象 Class<User> userClass = User.class; Object obj = userClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { Method setter = property.getWriteMethod(); if (setter != null) { setter.invoke(obj, map.get(property.getName())); } } System.out.println(obj); User user = new User(); user.setId(2L); user.setName("三省同学2"); //java对象转map Map<String, Object> map1 = new HashMap(); BeanInfo beanInfo1 = Introspector.getBeanInfo(user.getClass()); PropertyDescriptor[] propertyDescriptors1 = beanInfo1 .getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors1) { String key = property.getName(); if (key.compareToIgnoreCase("class") == 0) { continue; } Method getter = property.getReadMethod(); Object value = getter != null ? getter.invoke(user) : null; map1.put(key, value); } System.out.println(map1); }

相关文章