本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

Beanutils的简单使用

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


概述

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

关注文章首部微信公众号发送 #95_beanutils 获取依赖 jar 包。

使用

创建测试 JavaBean 如下:

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

属性的取值赋值

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}

拷贝属性值

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 数据

// 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}
# Java 杂项  

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×