BeanUtils,PropertyUtils

转自:http://www.cnblogs.com/friends-wf/p/3720348.html

beanUtils的用法

举例1:使用BeanUtils工具封装用户提交的数据。

复制代码
 1 public static void main(String[] args)throws Exception {
 2 
 3        // 模拟用户的输入的数据如下
 4 
 5        String name = "XML基础";
 6 
 7        String author = "焦宁波";
 8 
 9        String price = "99.99";
10 
11        String date = "2013-01-04";
12 
13        Book book = new Book();
14 
15        // 任务是将以上的属性设置给指定的Book对象
16 
17        BeanUtils.setProperty(book, "name", name);
18 
19        BeanUtils.setProperty(book, "author", author);
20 
21        BeanUtils.setProperty(book, "price",price );
22 
23        // 查看属性是否封装好
24 
25        System.out.println(book);
26 
27 }
复制代码

 

发现使用上面的代码可以省略基本数据类型的转型的问题。进而提高代码的开发效率。

举例2:自定义一个类型转换器类。

复制代码
 1 public static void main(String[] args)throws Exception {
 2 
 3        // 模拟用户的输入的数据如下
 4 
 5        String name = "XML基础";
 6 
 7        String author = "焦宁波";
 8 
 9        String price = "99.99";
10 
11        String date = "2013-01-04";
12 
13       
14 
15        Book book = new Book();
16 
17       
18 
19        // 注册一个自己的转换器
20 
21        /**
22 
23         * converter指定具体的转换器
24 
25         * clazz遇到什么类型调用上面的转换器
26 
27         */
28 
29        ConvertUtils.register(
30 
31               new Converter(){
32 
33               // 回调方法  
34 
35               @Override
36 
37               public Object convert(Class type, Object value) {
38 
39                   if(value == null){
40 
41                      return null;
42 
43                   }
44 
45                   // 转换为String
46 
47                   String data = (String)value;
48 
49                   // 将指定格式的字符串转换为Date
50 
51                   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
52 
53                   Date date  = null;
54 
55                   try {
56 
57                      date = format.parse(data);
58 
59                      return date;
60 
61                   } catch (ParseException e) {
62 
63                      e.printStackTrace();
64 
65                      return null;
66 
67                   }
68 
69               }
70 
71               },
72 
73               Date.class);
74 
75        // 任务是将以上的属性设置给指定的Book对象
76 
77        BeanUtils.setProperty(book, "name", name);
78 
79        BeanUtils.setProperty(book, "author", author);
80 
81        BeanUtils.setProperty(book, "price",price );
82 
83        BeanUtils.setProperty(book, "date",date );
84 
85        // 查看属性是否封装好
86 
87        System.out.println(book);
88 
89 }
复制代码

 

如果每次遇到一个复杂类型都需要自定义转换器,那样的话实在麻烦。大家看在开发的时候可以先查看该接口是否提供了有效的实现类。

ConvertUtils.register(new DateLocaleConverter(), Date.class);

其实真正的封装好的数据需要存储在数据库中,那么javabean的数据类型应该和数据库的数据类型保持一致,那么在声明持久化javabean的时候需要全部为数据库的基本数据类型。

因此大家在JavaBean中需要导入的是java.sql.Date类,这样就直接可以将日期自动转换了。

举例3:实现封装好的JavaBean对象的属性拷贝。

复制代码
1 // 实现属性封装数据的一个拷贝
2 
3 Book copy = new Book();
4 
5 System.out.println(copy);
6 
7 PropertyUtils.copyProperties(copy, book);
8 
9 System.out.println(copy);
复制代码

 

思考:如果使用BeanUtils封装用户的数据,那么也就是一个一个设置啊?岂不是也很麻烦?

其实在真是的环境中我们可以直接获取用户提交的所有的数据信息,只需要进行遍历即可,但是为了方便快速的设置,那么可以将javabean中的属性名和用户提交的数据名保持一致。


1、 BeanUtils一共分4个包:

 

 org.apache.commons.beanutils

 org.apache.commons.beanutils.converters

 org.apache.commons.beanutils.locale

 org.apache.commons.beanutils.locale.converters

 

其中上面两个是BeanUtils的默认实现,它没有针对本地化的任何处理,这个可以提高执行效率。

但是若你的程序对于本地化有要求的话,那还是使用下面2个包比较安全。

 

 org.apache.commons.beanutils

 

 这个包主要提供用于操作JavaBean的工具类,Jakarta-Common-BeanUtils的主要功能都在这个包里实现。

 

 

 

2、BeanUtils可以直接get和set一个属性的值。它将property分成3种类型:   

 

       Simple——简单类型,如Stirng、Int……   

 

       Indexed——索引类型,如数组、arrayList……   

 

       Maped——这个不用说也该知道,就是指Map啦,比如HashMap……   

 

       访问不同类型的数据可以直接调用函数getProperty和setProperty。getProperty只有2个参数,第一个是JavaBean对象,第二个是要操作的属性名;setProperty提供三个参数,第一是JavaBean对象,第二个是要操作的属性名,第三个为要设置的具体的值


public class Company { private String name; private HashMap address = new HashMap(); private String[] otherInfo; private ArrayList product; private ArrayList employee; private HashMap telephone; public Company(){} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress(String type) { return address.get(type).toString(); } public void setAddress(String type, String address) { this.address.put(type,address); } public String[] getOtherInfo() { return otherInfo; } public void setOtherInfo(String[] otherInfo) { this.otherInfo = otherInfo; } public ArrayList getProduct() { return product; } public void setProduct(ArrayList product) { this.product = product; } public ArrayList getEmployee() { return employee; } public void setEmployee(ArrayList employee) { this.employee = employee; } public HashMap getTelephone() { return telephone; } public void setTelephone(HashMap telephone) { this.telephone = telephone; } }
   

 

(1)Simple

//对于Simple类型,参数二直接是属性名即可

 System.out.println(BeanUtils.getProperty(c, "name"));

 

(2)Map

//对于Map类型,则需要以“属性名(key值)”的形式

 System.out.println(BeanUtils.getProperty(c, "address (A2)"));

 HashMap am = new HashMap();

am.put("1","234-222-1222211");

am.put("2","021-086-1232323");

 BeanUtils.setProperty(c,"telephone",am);

System.out.println(BeanUtils.getProperty(c, "telephone (2)"));

 

Map类型也可以采用BeanUtils.getMappedProperty(c, "address","A2");

 

(3)index 

//对于Indexed,则为“属性名[索引值]”,注意这里对于ArrayList和数组都可以用一样的方式进行操作。

System.out.println(BeanUtils.getProperty(c, "otherInfo[2]"));

BeanUtils.setProperty(c, "product[1]", "NOTES SERVER");

System.out.println(BeanUtils.getProperty(c, "product[1]"));

 

index类型还可以采用BeanUtils.getIndexedProperty(c,"product",1);

 

 (4)nest 3种类也可以组合使用啦!

System.out.println(BeanUtils.getProperty(c, "employee[1].name"));

 

3、bean copy功能 

 

       Company c2 = new Company();

       BeanUtils.copyProperties(c2, c);

 

       但是这种copy都是浅拷贝,复制后的2个Bean的同一个属性可能拥有同一个对象的ref,这个在使用时要小心,特别是对于属性为自定义类的情况

 

 

4、 BeanUtils和PropertyUtils

       这两个类几乎有一摸一样的功能,唯一的区别是:BeanUtils在对Bean赋值是会进行类型转化。举例来说也就是在copyProperty时只要属性名相同,就算类型不同,BeanUtils也可以进行copy;而PropertyBean则可能会报错!!

       针对上面的例子,新建一个Company2的类,其中代码与Company一样,只是将otherinfo从String[]改为String。

      Company c = init();

      Company2 c2 = new Company2();

     

      BeanUtils.copyProperties(c2,c);

//    PropertyUtils.copyProperties(c2,c); 这句会报错!!

      System.out.println(c2.getOtherInfo());

    当然2个Bean之间的同名属性的类型必须是可以转化的,否则用BeanUtils一样会报错。

       若实现了org.apache.commons.beanutils.Converter接口则可以自定义类型之间的转化。

由于不做类型转化,用PropertyUtils在速度上会有很大提高!

此外,不作类型转化还有一个好处,如下面的代码:

      //test data type convert

//    ArrayList a1 = BeanUtils.getProperty(c,"product"); //BeanUtils返回的是String

      System.out.println("--" + BeanUtils.getProperty(c,"product"));     //取出后直接被转为String

      ArrayList a = (ArrayList)PropertyUtils.getProperty(c,"product");//PropertyUtils返回的是Object

      System.out.println("--" + a.get(1));

用BeanUtils无法返回一个对象(除非自己写一个Converter),它会自动进行类型转化,然后返回String。对于想返回java类或自定义类的话,还是请使用PropertyUtils

 

5、Utils类

       所有的XXXUtils类都提供的是静态方法,可以直接调用,其主要实现都在相应的XXXUtilsBean中:

BeanUtils     ——> BeanUtilsBean

       ConvertUtils  ——> ConvertUtilsBean

    PropertyUtils ——> PropertyUtilsBean

 (1)PropertyUtils,获取属性的Class类型

public static Class getPropertyType(Object bean, String name)

(2)ConstructorUtils,动态创建对象

 public static Object invokeConstructor(Class klass, Object arg)

(3)MethodUtils,动态调用方法

 MethodUtils.invokeMethod(bean, methodName, parameter);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值