網頁

2014年2月11日 星期二

Commons Beanutils使用getProperty()

如果不使用getter/setter,訪問bean內的field的話,Apache Commons Beanutils提供了getProperty()來處理,透過BeanUtils的靜態方法,取得field的方法,給定field的名稱,可以用 "." 的表示法,利用這個方法,Mix可以很方便地取得field值。




Mix建立了1個bean:Author,只有2個屬性,同時在Magazine上,加上Author的field,並實作getter/setter。
  1. id:唯一識別碼。
  2. name:名稱。

Author

package org.openyu.java.commons.beanutils;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * The Class Author.
 */
public class Author {

 /** The id. */
 private long id;

 /** The name. */
 private String name;

 /**
  * Instantiates a new author.
  */
 public Author() {
 }

 /**
  * Gets the id.
  *
  * @return the id
  */
 public long getId() {
  return id;
 }

 /**
  * Sets the id.
  *
  * @param id
  *            the new id
  */
 public void setId(long id) {
  this.id = id;
 }

 /**
  * Gets the name.
  *
  * @return the name
  */
 public String getName() {
  return name;
 }

 /**
  * Sets the name.
  *
  * @param name
  *            the new name
  */
 public void setName(String name) {
  this.name = name;
 }

 /*
  * (non-Javadoc)
  *
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
  return new ToStringBuilder(this)
  //return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
    .append("id", id)
    .append("name", name)
    .toString();
 }

}



Magazine

/**
 * The Class Magazine.
 */
public class Magazine {
        ...
 /** The author. */
 private Author author;
        ...
}






getProperty()

取得bean指定名稱的field值。

 @Test
 public void getProperty() throws Exception {
  Magazine magazine = new Magazine();
  magazine.setId(1L);
  magazine.setName("OpenYu");
  magazine.setPrice(1000);

  String id = BeanUtils.getProperty(magazine, "id");
  String name = BeanUtils.getProperty(magazine, "name");
  String price = BeanUtils.getProperty(magazine, "price");

  // 不存在field,會拋出NoSuchMethodException
  // String notExist = BeanUtils.getProperty(magazine, "notExist");

  System.out.println("id = " + id + ", name = " + name + ", price ="
    + price);
  //
  assertEquals("1", id);
  assertEquals("OpenYu", name);
  assertEquals("1000", price);
 }



console查看其結果。

id = 1, name = OpenYu, price =1000



getNestedProperty()

取得bean指定名稱的field值。

 @Test
 public void getNestedProperty() throws Exception {
  Magazine magazine = new Magazine();
  magazine.setId(1L);
  magazine.setName("OpenYu");
  magazine.setPrice(1000);

  // author
  Author author = new Author();
  author.setId(1L);
  author.setName("Java");
  magazine.setAuthor(author);
  //
  String authorName = (String) BeanUtils.getNestedProperty(magazine,
    "author.name");
  System.out.println("Author Name: " + authorName);
  assertEquals("Java", authorName);
 }



console查看其結果。

Author Name: Java












Mix取得的值,都是String,想要取得原型別,需自行轉換,Commons BeanutilsgetProperty()有點不方便轉換型別。



沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...