java之beanutils使用

时间:2024-12-08 23:33:32

介绍

BeanUtils是Apache Commons组件的成员之一, 主要用于简化JavaBean封装数据的操作。 ​

点击下载依赖 jar 包

使用

有如下 javabean :

package com.zze.bean;

import java.util.Date;

public class User {
    public User() {
    }

    public User(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    private String name;
    private Integer age;
    private Date birthday;

    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;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}

com.zze.bean.User

属性的取值赋值

@Test
public void test1() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    User user = new User();
    BeanUtils.setProperty(user, "name", "zhangsan");
    String name = BeanUtils.getProperty(user, "name");
    System.out.println(name); // zhangsan
    System.out.println(user); // User{name='zhangsan', age=null, birthday=null}
}

拷贝属性值

@Test
public void test2() throws InvocationTargetException, IllegalAccessException {
    User from = new User("zhangsan", 15, new Date());
    User to = new User();
    BeanUtils.copyProperties(to, from);
    System.out.println(to); // User{name='zhangsan', age=15, birthday=Mon Jan 14 12:17:48 CST 2019}
}

封装Map数据

@Test
    public void test3() throws InvocationTargetException, IllegalAccessException {
        // ConvertUtils.register(new DateLocaleConverter(),Date.class);
        // 自定义 String 到 Date 的转换器
        ConvertUtils.register(new Converter() {
            public Object convert(Class type, Object value) {

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    return simpleDateFormat.parse(value.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }, Date.class);
        Map<String, String> userMap = new HashMap<>();
        userMap.put("name", "zhangsan");
        userMap.put("age", "18");
        userMap.put("birthday", "2018-1-1");
        User user = new User();
        BeanUtils.populate(user, userMap);
        System.out.println(user); // User{name='zhangsan', age=18, birthday=Mon Jan 01 00:00:00 CST 2018}
    }