BeanUtils介绍及其使用

BeanUtils工具由Apache软件基金组织编写,提供给我们使用,主要解决的问题是:把对象的属性数据封装到对象中。在整个J2EE的编程过程中,我们经常会从各种配置文件中读取相应的数据,需要明白的一点是从配置文件中读取到的数据都是String,但是很显然我们的应用程序中不仅仅有String一种数据类型,比如:基本数据类型(int、double、char、float等),还有自定义数据类型(引用数据类型),那么我们必须面临的一个问题就是讲字符串类型转换为各种具体的数据类型

有两种方法供我们是使用:

  • 首先判断需要的数据类型,然后对字符串类型调用相应的方法,将其转换为我们想要的类型

  • 使用BeanUtils工具

第一种存在的问题是太过于繁琐,每次都要进行大量的类型转换,Apache软件基金会给我们提供了第二种方法,使用其提供的BeanUtils工具,具体的说只需要知道其中的两个方法就能实现类型的转换,很简单,降低了编程的难度。


很明显,要想使用别人开发的工具必须将其jar包导入到程序中,但是BeanUtils包存对另外一个软件包的依赖,下面将具体的显示jar包的名字,其中的版本号不一定与我使用的相同。


Beanutils工具在使用时几乎只用到以下几个方法,其中一个方法通常情况下都是使用匿名内部类。

  • BeanUtils.setProperty(bean, name, value);其中bean是指你将要设置的对象,name指的是将要设置的属性(写成”属性名”),value(从配置文件中读取到到的字符串值)
  • BeanUtils。copyProperties(bean, name, value),和上面的方法是完全一样的。使用哪个都可以
  • ConvertUtils.register(Converter converter , ..),当需要将String数据转换成引用数据类型(自定义数据类型时),需要使用此方法实现转换。
  • BeanUtils.populate(bean,Map),其中Map中的key必须与目标对象中的属性名相同,否则不能实现拷贝。
  • BeanUtils.copyProperties(newObject,oldObject),实现对象的拷贝

自定义数据类型使用BeanUtils工具时必须具备的条件

自定义数据类型使用BeanUtils工具时,本身必须具备getter和setter方法,因为BeanUtils工具本身也是一种内省的实现方法,所以也是借助于底层的getter和setter方法进行转换的。

封装成javabean的对象

 1 public class Emp {
 2     private int id ;
 3     private String name;
 4     public Emp(int id, String name, double salary, Date date) {
 5         super();
 6         this.id = id;
 7         this.name = name;
 8         this.salary = salary;
 9         this.date = date;
10     }
11 
12     private double salary;
13     private Date date;
14 
15 
16     public Date getDate() {
17         return date;
18     }
19     public void setDate(Date date) {
20         this.date = date;
21     }
22     public Emp() {
23 
24     }
25 
26     public int getId() {
27         return id;
28     }
29     public void setId(int id) {
30         this.id = id;
31     }
32     public String getName() {
33         return name;
34     }
35     public void setName(String name) {
36         this.name = name;
37     }
38     public double getSalary() {
39         return salary;
40     }
41     public void setSalary(double salary) {
42         this.salary = salary;
43     }
44 
45 
46     @Override
47     public String toString() {
48         // TODO Auto-generated method stub
49         return "编号:"+this.id+" 姓名:"+this.name+" 工资:"+this.salary+" 生日:"+date;
50     }
51 
52 }

使用BeanUtils组件进行转换

 1 /**
 2  * BeanUtils工具的使用
 3  * 功能:BeanUtils主要是用于将对象的属性封装到对象中
 4  * BeanUtils的好处:
 5  * BeanUtils设置属性值的时候,如果属性是基本数据类型,那么BeanUtils会自动帮我们进行数据类型的转换,并且
 6  * BeanUtils设置属性的时候也是依赖于底层的getter和setter方法
 7  * 
 8  * 如果设置的属性值是其他的引用数据类型,此时必须要注册一个类型转换器才能实现自动的转换
 9  * */
10 
11 
12 import java.lang.reflect.InvocationTargetException;
13 import java.text.ParseException;
14 import java.text.SimpleDateFormat;
15 import java.util.Date;
16 
17 import javax.xml.crypto.Data;
18 
19 import org.apache.commons.beanutils.BeanUtils;
20 import org.apache.commons.beanutils.ConvertUtils;
21 import org.apache.commons.beanutils.Converter;
22 import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
23 
24 public class BeanUtils {
25     public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
26         //从文件中读取到的数据都是字符串的数据,或者是表单提交的数据获取到的时候也是字符串数据
27         //在J2EE的编程中,我们会通过配置文件或者直接从文件获取数据的方式得到我们想要的数据
28         //那么就存在一个问题,当我们需要的是一个int时,读到的数据确是String,那么我们每次是不是都要先判断实际
29         //需要的是什么数据类型,然后进行一个强制的类型转换呢?回答是不需要,我们借助Apache软件基金会提供的BeanUtils工具
30         //根本不用管什么样的数据类型,只需要使用BeanUtils的setProperties方法,该方法有三个参数,对三个参数进行设置便会
31         //实现自动的数据类型转换
32 
33         /*ConvertUtils.register(new Converter() {
34 
35 
36             //自定义日期类型转换器
37             @Override
38             public Object convert(Class  type, Object value) { //type:目前需要转换的数据类型 value:目前参数的值
39                 //目标:将字符串转换为日期
40 
41                 if(type != Date.class)  return null;
42 
43                 if (value == null || "".equals(value.toString().trim())) {
44                     return null;
45                 }
46                 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
47                 Date date = null;
48                 try {
49                      date = dateFormat.parse((String)value);
50                 } catch (ParseException e) {
51                     throw new RuntimeException(e);
52                 }
53                 return date;
54             }
55         }, Date.class);  //Date.class表示要转换的成引用类型,Date类型不是基本数据类型,所以需要一个转换器进行相应的转换,同样该功能属于BeanUtils
56         */
57 
58         //使用日起转换器工具类
59         ConvertUtils.register(new DateLocaleConverter(), Date.class);   //不灵活,自己实现最好
60 
61         String id ="110";  //我们用这个三个String类型的属性代表从配置文件中读取到的数据,实际编程过程中这些数据直接从properties文件中读取
62         String name = "朱君鹏";
63         String salary = "1000";
64 //        String birthday = "2015年01月30日"; //如果要使用工具中提供的转换器必须要符合一定的格式,像这种格式就不能实现转换
65         String birthday = "2015-01-30";  //该格式可以实现使用工具提供的转换器类将字符串正确的转换,
66 
67 
68         Emp p = new Emp();  //读取到数据之后,对该对象的属性进行设置,使用BeanUtils工具可以避免强制类型的转换,但是在Emp类中的每个属性都要有getter和setter方法
69                              //因为BeanUtils工具实际上是对内省的封装,使其更加的好用,所以其底层还是依赖getter和setter方法
70 
71         BeanUtils.setProperty(p, "id", id);  //其中p代表的是要设置的对象
72 
73         BeanUtils.setProperty(p, "name", name);   //中间一个参数代表的是要设置的属性
74 
75         BeanUtils.setProperty(p, "salary", salary); //第三个参数代表的是第二个属性的值
76 
77         BeanUtils.setProperty(p, "date", birthday);
78 
79         System.out.println(p);
80     }
81 }
BeanUtils.populate(bean,Map)
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> map = request.getParameterMap();
		Map<String, String> output = new HashMap<String, String>();
		for(Entry<String, String[]> entry : map.entrySet()) {
			output.put(entry.getKey(), entry.getValue()[0]);
		}
		Domain formDomain = new Domain();
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		try {
			BeanUtils.populate(formDomain, map);
		} catch (IllegalAccessException | InvocationTargetException e) {
			throw new RuntimeException(e);
		}
		System.out.println(formDomain.toString());
	}

  

原文地址:https://www.cnblogs.com/wdpnodecodes/p/7802111.html