Beanutils

本文详细介绍了Apache Commons BeanUtils库的强大功能,包括动态getter和setter、动态排序、属性转换及更多的实用工具方法,展示了如何简化Java Bean操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Beanutils用了魔术般的反射技术,实现了很多夸张有用的功能,都是C/C++时代不敢想的。无论谁的项目,始终一天都会用得上它。我算是后知后觉了,第一回看到它的时候居然错过。

1.属性的动态getter,setter

在这框架满天飞的年代,不能事事都保证执行getter,setter函数了,有时候属性是要需要根据名字动态取得的,就像这样:  
BeanUtils.getProperty(myBean,"code");
而BeanUtils更强的功能是直接访问内嵌对象的属性,只要使用点号分隔。
BeanUtils.getProperty(orderBean, "address.city");
相比之下其他类库的BeanUtils通常都很简单,不能访问内嵌的对象,所以经常要用Commons BeanUtils替换它们。
BeanUtils还支持List和Map类型的属性。如下面的语法即可取得顾客列表中第一个顾客的名字
BeanUtils.getProperty(orderBean, "customers[1].name");
其中BeanUtils会使用ConvertUtils类把字符串转为Bean属性的真正类型,方便从HttpServletRequest等对象中提取bean,或者把bean输出到页面。
而PropertyUtils就会原色的保留Bean原来的类型。

2.beanCompartor 动态排序

还是通过反射,动态设定Bean按照哪个属性来排序,而不再需要在bean的Compare接口进行复杂的条件判断。
List peoples = ...; // Person对象的列表Collections.sort(peoples, new BeanComparator("age"));

如果要支持多个属性的复合排序,如"Order By lastName,firstName"

ArrayList sortFields = new ArrayList();sortFields.add(new BeanComparator("lastName"));
sortFields.add(new BeanComparator("firstName"));
ComparatorChain multiSort = new ComparatorChain(sortFields);
Collections.sort(rows,multiSort);

其中ComparatorChain属于jakata commons-collections包。
如果age属性不是普通类型,构造函数需要再传入一个comparator对象为age变量排序。
另外, BeanCompartor本身的ComparebleComparator, 遇到属性为null就会抛出异常, 也不能设定升序还是降序。
这个时候又要借助commons-collections包的ComparatorUtils.

   Comparator mycmp = ComparableComparator.getInstance();
   mycmp = ComparatorUtils.nullLowComparator(mycmp);  //允许null
   mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序
   Comparator cmp = new BeanComparator(sortColumn, mycmp);

3.Converter 把Request或ResultSet中的字符串绑定到对象的属性

   经常要从request,resultSet等对象取出值来赋入bean中,下面的代码谁都写腻了,如果不用MVC框架的绑定功能的话。

   String a = request.getParameter("a");   bean.setA(a);   String b = ....

不妨写一个Binder:

     MyBean bean = ...;    HashMap map = new HashMap();    Enumeration names = request.getParameterNames();    while (names.hasMoreElements())    {      String name = (String) names.nextElement();      map.put(name, request.getParameterValues(name));    }    BeanUtils.populate(bean, map);

    其中BeanUtils的populate方法或者getProperty,setProperty方法其实都会调用convert进行转换。
    但Converter只支持一些基本的类型,甚至连java.util.Date类型也不支持。而且它比较笨的一个地方是当遇到不认识的类型时,居然会抛出异常来。
    对于Date类型,我参考它的sqldate类型实现了一个Converter,而且添加了一个设置日期格式的函数。
要把这个Converter注册,需要如下语句:

    ConvertUtilsBean convertUtils = new ConvertUtilsBean();

    DateConverter dateConverter = new DateConverter();

    convertUtils.register(dateConverter,Date.class);







//因为要注册converter,所以不能再使用BeanUtils的静态方法了,必须创建BeanUtilsBean实例

BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils,new PropertyUtilsBean());

beanUtils.setProperty(bean, name, value);
4 其他功能
4.1 PropertyUtils,当属性为Collection,Map时的动态读取:
 
Collection: 提供index
   BeanUtils.getIndexedProperty(orderBean,"items",1);
或者
  BeanUtils.getIndexedProperty(orderBean,"items[1]");

Map: 提供Key Value
  BeanUtils.getMappedProperty(orderBean, "items","111");//key-value goods_no=111
或者
  BeanUtils.getMappedProperty(orderBean, "items(111)")
 
4.2 PropertyUtils,获取属性的Class类型
     public static Class getPropertyType(Object bean, String name)
 
4.3 ConstructorUtils,动态创建对象
      public static Object invokeConstructor(Class klass, Object arg)
4.4 MethodUtils,动态调用方法
    MethodUtils.invokeMethod(bean, methodName, parameter);
4.5 动态Bean 用DynaBean减除不必要的VO和FormBean 
### Apache Commons BeanUtils 使用方法与示例 #### 1. 添加依赖 为了使用 `BeanUtils`,需要先引入 Apache Commons BeanUtils 库。如果项目基于 Maven 构建,则可以通过修改 `pom.xml` 文件添加以下依赖[^2]: ```xml <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.4</version> </dependency> ``` 对于非 Maven 项目,可以从官方仓库下载 JAR 包并手动将其加入项目的类路径。 --- #### 2. 基本功能介绍 `BeanUtils` 提供了一系列静态方法来简化 JavaBeans 属性的操作,主要包括以下几个方面: - **属性复制 (`copyProperties`)**:将源对象的属性值复制到目标对象。 - **属性设置 (`setProperty`)**:动态设置指定名称的属性值。 - **属性获取 (`getProperty`)**:动态获取指定名称的属性值。 - **批量操作**:支持对多个属性进行统一处理。 以下是具体的功能实现和代码示例。 --- #### 3. 示例代码 ##### (1)属性复制 (`copyProperties`) 此方法可以将一个对象的属性值复制到另一个具有相同属性的对象中。假设我们有两个类 `Source` 和 `Target`,它们拥有相同的字段结构。 ```java import org.apache.commons.beanutils.BeanUtils; class Source { private String name; private int age; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Target { private String name; private int age; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class CopyPropertiesExample { public static void main(String[] args) throws Exception { Source source = new Source(); source.setName("John"); source.setAge(30); Target target = new Target(); // 复制属性 BeanUtils.copyProperties(target, source); System.out.println("Name: " + target.getName()); // 输出 John System.out.println("Age: " + target.getAge()); // 输出 30 } } ``` 以上代码展示了如何利用 `BeanUtils.copyProperties` 方法完成两个对象之间的属性同步[^3]。 --- ##### (2)动态设置属性值 (`setProperty`) 该方法允许通过字符串形式的键名动态设置对象的某个属性值。 ```java import org.apache.commons.beanutils.BeanUtils; class Person { private String firstName; private String lastName; // Getters and Setters public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } public class SetPropertyExample { public static void main(String[] args) throws Exception { Person person = new Person(); // 动态设置属性值 BeanUtils.setProperty(person, "firstName", "Alice"); BeanUtils.setProperty(person, "lastName", "Smith"); System.out.println("First Name: " + person.getFirstName()); // 输出 Alice System.out.println("Last Name: " + person.getLastName()); // 输出 Smith } } ``` 上述代码片段说明了如何通过反射机制调用 setter 方法为对象赋值[^4]。 --- ##### (3)动态获取属性值 (`getProperty`) 类似于 `setProperty`,也可以通过 `getProperty` 获取对象的特定属性值。 ```java import org.apache.commons.beanutils.BeanUtils; class Product { private double price; // Getter and Setter public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } public class GetPropertyExample { public static void main(String[] args) throws Exception { Product product = new Product(); product.setPrice(19.99); // 动态获取属性值 String result = BeanUtils.getProperty(product, "price"); System.out.println("Product Price: " + result); // 输出 19.99 } } ``` 此处展示的是如何提取对象内部的数据而无需显式调用 getter 方法。 --- #### 4. 注意事项 - 如果源对象和目标对象之间存在不匹配的属性(如类型不同),可能会抛出异常。 - 对于复杂类型的嵌套属性访问,需确保中间层已初始化,否则会引发 NullPointerException。 - 需要捕获可能发生的 `IllegalAccessException` 或 `InvocationTargetException` 异常。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值