如鹏网 大学生计算机学习社区

CowNew开源团队

http://www.cownew.com 邮件请联系 about521 at 163.com

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  363 随笔 :: 2 文章 :: 808 评论 :: 0 Trackbacks
BeanUtils
BeanUtils是Apache-Commons项目提供的另一个非常方便的类库,通过这个类库能够更方便的使用反射。最常用的类是BeanUtils(org.apache.commons.beanutils包中),使用这个类能通过名字访问一个Bean中的某个属性。
通过BeanUtils.getProperty(person,”age”)能得到person的age属性。此方法还支持内嵌对象,比如BeanUtils.getProperty(person,”manager.name”)就能得到person的manager属性的name属性。还支持List和Map类型的属性,如下面的语法即可取得Order的顾客列表中第一个顾客的名字BeanUtils.getProperty(orderBean, "customers[1].name")。 使用BeanUtils.setProperty方法则可以设置javaBean的属性值。
ConstructorUtils提供了调用构造函数的方法,使用public static Object invokeConstructor(Class klass, Object arg)可以直接调用某个类的构造函数。
MethodUtils提供了调用bean方法的方法,使用MethodUtils.invokeMethod(bean, methodName, parameter);可以直接调用某个类的某个方法。
PropertyUtils提供了更详细的属性访问方法,使用public static Class getPropertyType(Object bean, String name)获取属性的Class类型。
UserInfo userInfo = (UserInfo) ConstructorUtils.invokeConstructor(
    UserInfo.class, new Object[] {});
PersonInfo personInfo = (PersonInfo) ConstructorUtils
    .invokeConstructor(PersonInfo.class, new Object[] {});
BeanUtils.setProperty(personInfo, "age", new Integer(20));
BeanUtils.setProperty(personInfo, "name", "Tom");
BeanUtils.setProperty(userInfo, "number", "admin");
  BeanUtils.setProperty(userInfo, "person", personInfo);
System.out.println(BeanUtils.getProperty(userInfo, "person.name"));
BeanUtils.setProperty(userInfo, "person.name","xdx");
System.out.println(BeanUtils.getProperty(userInfo, "person.name"));
System.out.println(PropertyUtils.getPropertyType(userInfo,"person"));
运行结果:
Tom
xdx
class com.cownew.PIS.basedata.common.PersonInfo
posted on 2007-02-05 12:49 CowNew开源团队 阅读(755) 评论(1)  编辑  收藏

评论

# re: xjl:BeanUtils 2007-02-09 14:00 坏男孩
...................★
..................▍..★
..................▍.一 .☆
................. ▍ ..帆. ★
..................▍ ... 风. ☆
..................▍ ... ..顺. ★
................. ▍.万 事 如 意. ☆
..................▍☆ .★ .☆ .★. ☆
..................▍
 ..▍∵ ☆ ★...▍▍....█▍ ☆ ★∵▍..
   ◥█▅▅██▅▅██▅▅▅▅▅███◤
   .◥███████████████◤
 ~~~~◥█████████████◤~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: