HashMap 转化为Bean对象

首先吐槽一下百度,我确信网上肯定是有现成轮子的,只是我们搜不到!!! 搜到的都是自己造的轮子,如图

 

HashMap 转化为Bean对象_第1张图片

 

 

那有么有比较官方的呢?当然有了!不过我是用google搜索到的。

 

HashMap 转化为Bean对象_第2张图片

 

 

我们明确可以看到BeanUtils字样,所以我们在maven仓库中进行搜索,果然有这个东西。所以下面是这个类的使用方法

导入必要库

         
         
            commons-beanutils 
            commons-beanutils 
            1.9.3 
        

自定义Map:SimpleMap

public class SimpleMap extends HashMap implements Serializable { 
 
    private static final long serialVersionUID = -5809782578272943999L; 
 
    public Object toBean(Class clazz){ 
        try { 
            Object obj = clazz.newInstance(); 
            BeanUtils.populate(obj,this); 
            return obj; 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return null; 
    } 
}

然后我们使用的时候就可以使用SimpleMap来代替HashMap了,如下:

 

HashMap 转化为Bean对象_第3张图片

 

 

 

HashMap 转化为Bean对象_第4张图片

 

 

其他相关源码:

    @Test 
    public  void studentTest(){ 
        SimpleMap map = new SimpleMap(); 
        map.put("name","tao"); 
        map.put("age",18); 
        Student student = (Student) map.toBean(Student.class); 
        System.out.println(student); 
    } 
public class Student { 
    private Integer id; 
 
    private Integer age; 
 
    private String name; 
 
    public Integer getId() { 
        return id; 
    } 
 
    public void setId(Integer id) { 
        this.id = id; 
    } 
 
    public Integer getAge() { 
        return age; 
    } 
 
    public void setAge(Integer age) { 
        this.age = age; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name == null ? null : name.trim(); 
    } 
}

参考资料

  • How to convert HashMap to JavaBean

你可能感兴趣的:(Java)