1. 程式人生 > >JAVA工具包_BeanUtils

JAVA工具包_BeanUtils

自定義 直接 thread back 試用 ng- pad 乒乓球 util

簡介

大多數的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 \n Before:\n" + user);
        Hobby hobby = new Hobby("籃球", "每天一小時,健康一輩子");
        BeanUtils.setProperty(user, "hobby", hobby);
        System.out.println("After:\n" + user);
        // 設置自定義對象屬性方法二,這裏需要註意,如果hobby為null,
        // 則這樣是設置值是設置不進去的,只有當對象不為空的時候才能設置進去
        System.out.println("WayTwo \n Before:\n" + 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:\n" + user);
    
    }

}

JAVA工具包_BeanUtils