BeanUtils

/*
 BeanUtils:
 BeanUtils主要解决 的问题: 把对象的属性数据封装 到对象中。
 BeanUtils的好处:
     1. BeanUtils设置属性值的时候,如果属性是基本数据 类型,BeanUtils会自动帮我转换数据类型。
      2. BeanUtils设置属性值的时候底层也是依赖于get或者Set方法设置以及获取属性值的。
      3. BeanUtils设置属性值,如果设置的属性是其他的引用 类型数据,那么这时候必须要注册一个类型转换器。     
 BeanUtilss使用的步骤:
     1. 导包commons-logging.jar 、 commons-beanutils-1.8.0.jar
 */

public class Demo {
    public static void main(String[] args) throws Exception {
        //BeanUtils自动把字符串转为对应的数据类型,
        //配置文件中读取到的字符串,表单提交的字符串
        String id="1";
        String name="小明";
        String salary="11.222";
        String birthday="1991-01-02";
        ConvertUtils.register(new Converter() {
            @Override
            public Object convert(Class type, Object value) {//
                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
                Date date=null;
                try {
                   date=format.parse((String) value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return date;
            }
        }, Date.class);
        
        Person p=new Person();
        BeanUtils.setProperty(p, "id",id);
        BeanUtils.setProperty(p, "name", name);
        BeanUtils.setProperty(p, "salary", salary);
        BeanUtils.setProperty(p, "birthday", birthday);
        System.out.println(p);
    }
}
public class Person {
    private int id;
    private String name;
    private double salary;
    private Date birthday;
    
    public int getId() {
        return id;
    }
    public Person(int id, String name, double salary, Date birthday) {
        super();
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }
    public Person(){
        
    }
    @Override
    public String toString() {
        return "编号"+id+" 姓名"+name+" 工资"+salary+" 生日"+birthday;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}


转载于:https://my.oschina.net/k2easy/blog/537602

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值