简介
大多数的java开发者通常在创建Java类的时候都会遵循JavaBean的命名模式,对类的属性生成getters方法和setters方法。通过调用相应的getXxx和setXxx方法,直接访问这些方法是很常见的做法。BeanUtils就是一种方便我们对JavaBean进行操作的工具,是Apache组织下的产品。
前提
- commons-beanutils-1.9.3.jar
- commons-logging-1.2.jar(由于commons-beanutils-1.9.3.jar依赖与commons-loggin否则会报错:Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory)
代码清单,测试用的JavaBean:User.java
public class User { // 姓名 private String userName; // 年龄 private int age; // 生日 private Date birthday; public User() { } public User(String userName, int age) { this.userName = userName; this.age = age; } public User(String userName, int age, Date birthday) { this.userName = userName; this.age = age; this.birthday = birthday; } public int getAge() { return this.age; } public String getUserName() { return this.userName; } public void setAge(int age) { this.age = age; } public void setUserName(String userName) { this.userName = userName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "User [userName=" + userName + ", age=" + age + ", birthday=" + birthday + "]"; } }
测试代码清单
public class BeanUtilsDemo { public static void main(String[] args) throws Exception { User user = new User("Jim", 1, new Date(123456798)); // 获取属性值 System.out.println("userName :" + BeanUtils.getProperty(user, "userName")); // 设置引用类型属性 BeanUtils.setProperty(user, "userName", "testBeanUtils"); System.out.println("user = " + user); // 设置对象类型属性方法一 BeanUtils.setProperty(user, "birthday", new Date(987652122564L)); System.out.println("user = " + user); // 设置对象类型属性方法二 BeanUtils.setProperty(user, "birthday.time", 45641246546L); System.out.println("user = " + user); // 设置自定义对象属性方法一 System.out.println("WayOne Before: " + user); Hobby hobby = new Hobby("篮球", "每天一小时,健康一辈子"); BeanUtils.setProperty(user, "hobby", hobby); System.out.println("After: " + user); // 设置自定义对象属性方法二,这里需要注意,如果hobby为null, // 则这样是设置值是设置不进去的,只有当对象不为空的时候才能设置进去 System.out.println("WayTwo Before: " + user); BeanUtils.setProperty(user, "hobby.hobbyName", "乒乓球"); System.out.println("user = " + user); BeanUtils.setProperty(user, "hobby", null); BeanUtils.setProperty(user, "hobby.desc", "我国乒乓第一,我爱国"); System.out.println("After: " + user); } }