map和bean相互转换
map和bean的相互转换需要使用jar包maven地址:
<dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> </dependency>
map和bean相互转换的工具类方法:
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); BeanUtils.populate(obj, map); return obj; } public static Map<?, ?> objectToMap(Object obj) { if(obj == null) return null; return new BeanMap(obj); }
测试方法:
public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("age", 12); map.put("name", "张三"); try { User user = (User) mapToObject(map, User.class); System.err.println(user.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } User user1 = new User(); user1.setAge(22); user1.setName("李四"); @SuppressWarnings("unchecked") Map<String , Object> map2 = (Map<String, Object>) objectToMap(user1); System.err.println("map2:"+map2.get("age")+map2.get("name")); }
测试中需要一个bean:User.java
public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }