BeanUtils工具类的介绍与使用

xiaoxiao2021-02-28  85

在学习JavaWeb发现一个很好工具类Beanutils.

BeanUtils主要解决 的问题: 把对象的属性数据封装 到对象中。其底层也是用到内省。主要对get、set方法的操作。

BeanUtils的好处: 1. BeanUtils设置属性值的时候,如果属性是基本数据 类型,BeanUtils会自动帮我转换数据类型。 2. BeanUtils设置属性值的时候底层也是依赖于get或者Set方法设置以及获取属性值的。 3. BeanUtils设置属性值,如果设置的属性是其他的引用 类型数据,那么这时候必须要注册一个类型转换器。 BeanUtilss使用的步骤:

1. 导包commons-logging.jar 、 commons-beanutils-1.9.2.jar

commons-beanutils-1.9.2.jar下载地址: http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgicommons-logging.jar下载地址: https://commons.apache.org/proper/commons-logging/download_logging.cgi package Demo0; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; public class Demo3 { public static void main(String[] args) throws IllegalAccessException, InvocationTargetException { //从文件中读取到的数据都是字符串的数据,或者是表单提交的数据获取到的时候也是字符串的数据。 String id="001"; String name="科比"; String salary="100"; String birthday="2017-05-06"; //注册一个类型转换器 ConvertUtils.register(new Converter(){ // type : 目前所遇到的数据类型。 value :目前参数的值。 public Object convert(Class type,Object value){ Date date=null; try{ SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-mm-dd"); date=dateFormat.parse((String)value); }catch(Exception e){ e.printStackTrace(); } return date; } }, Date.class); Example e=new Example(); BeanUtils.setProperty(e, "id", id); BeanUtils.setProperty(e, "name", name); BeanUtils.setProperty(e, "salary", salary); BeanUtils.setProperty(e, "birthday", birthday); System.out.println(e); } } package Demo0; import java.util.Date; public class Example { private int id; private String name; private double salary; private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Example(int id, String name, double salary) { super(); this.id = id; this.name = name; this.salary = salary; } public int getId() { return id; } 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 Example(){ } public String toString() { return "编号:"+this.id+" 姓名:"+this.name+" 薪水"+this.salary+" 生日:"+birthday; } }
转载请注明原文地址: https://www.6miu.com/read-52835.html

最新回复(0)