2 Apache Commons BeanUtils

Wu Jun 2019-12-25 15:59:04
16 辅助工具类 > 1 Apache Commons

Commons BeanUtils官网

包结构


Package Description
org.apache.commons.beanutils 提供底层工具类,获取Bean属性值,动态定义和访问Bean属性。
org.apache.commons.beanutils.converters 一启动就预注册ConvertUtilsConverter 接口的实现
org.apache.commons.beanutils.expression Resolver 接口和实现

常用类


常用类都在顶层包中

(1) BeanUtils

通过反射操纵Bean属性,以下静态方法都是使用默认实例,通过使用BeanUtilsBean 可以提供更多复杂操作。

(2) ConstructorUtils

通过反射调用构造函数。

(3) ConvertUtils

可以自定义 Converter ,或使用ConvertUtilsBean中提供的多种实现,将其与一个类注册,然后调用convert方法进行转换类型

(4) MethodUtils

通过反射访问对象的方法并且执行方法

(5) PropertyUtils

通过反射操纵对象getter、setter方法的工具,具体实现由PropertyUtilsBean提供。

     Employee employee = ...;
     int index = ...;
     String name = "subordinate[" + index + "]";
     Employee subordinate = (Employee)
       PropertyUtils.getIndexedProperty(employee, name);

     Employee employee = ...;
     int index = ...;
     Employee subordinate = (Employee)
       PropertyUtils.getIndexedProperty(employee, "subordinate", index);
     Employee employee = ...;
     Address address = ...;
     PropertyUtils.setMappedProperty(employee, "address(home)", address);

     Employee employee = ...;
     Address address = ...;
     PropertyUtils.setMappedProperty(employee, "address", "home", address);
     String city = employee.getAddress("home").getCity();

PropertyUtils 提供 getNestedProperty(Object bean, String name) setNestedProperty(Object bean, String name, Object value)

     String city = (String)PropertyUtils.getNestedProperty(employee, "address(home).city");

getProperty(Object bean, String name) setProperty(Object bean, String name, Object value)

     Employee employee = ...;
     String city = (String) PropertyUtils.getProperty(employee, "subordinate[3].address(home).city");