java之beanutils使用
2024-09-21 16:41:01
介绍
BeanUtils是Apache Commons组件的成员之一, 主要用于简化JavaBean封装数据的操作。
使用
有如下 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} }
最新文章
- Shader实例:扭曲,漩涡
- 【OC简介-类和对象】
- bootstrap的下拉框在firefox界面不友好的处理
- Centos 安装了 Wkhtmltopdf 却依旧显示 无法打印pdf
- 深度学习笔记------linux下配置安装caffe-cpu only模式
- iOS国际化多语言设置
- JAVA 开发实例 一 移动的小球
- java源码研究--List中的set和add方法区别
- JavaScript之可运行按钮
- Protobuf语言指南
- 11g导入大量包含子分区的数据时表空间不足
- PLSQLDeveloper过期要注册表
- JBoss AS7(Application Server 7)的Standalone模式和Domain模式
- GC垃圾回收器
- FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(me
- Mysql 中json 相关函数的使用
- [转]iCheck表单美化插件使用方法详解(含参数、事件等)
- Android :Activity、Adapter、List的初步学习
- Django中表单的用法深探
- DOM节点中获取文本易混淆的属性