java Beanutils.copyProperties()

vo-->po,有大量的set代码,如:

User u=new User();
u.setName(vo.getName());
u.setAge(vo.getAge());

这种对JavaBean的属性的处理,占据大量的get/set代码,使用了BeanUtils.copyProperties()方法后,代码就减少很多了.
vo

public class UserForm {
    private int age;
    private String name;
    private int kk;
    public int getKk() {
        return kk;
    }
    public void setKk(int kk) {
        this.kk = kk;
    }
    public UserForm(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

po

public class User {
    private int id;
    private int age;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String toString(){
        return "User: id="+id+" name="+name+" age="+age;
    }
}
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        UserForm uf=new UserForm(18,"laly");
        User user=new User();
        //
        BeanUtils.copyProperties(uf,user);
        System.out.println(user.toString());
    }

输出:
User: id=0 name=laly age=18
如果User和UserForm 间存在名称不相同的属性,则BeanUtils不对这些属性进行处理,需要手动处理

 


作者:l老神仙l
链接:https://www.jianshu.com/p/3e2058fc3e72
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/xxl910/p/12915448.html