commons-beanutils.jar可以到Apache官網的commons子項目下找到它,或者,在Struts2,Spring的下載包中也能看到它的影子。單獨使用時,要多引進一個commons-logging.jar,這個包也是非常見的,可在有commons-beanutils.jar的地方找到它。
好,我們來測試一下,怎么使用這個類庫中的兩個常用類及它的常用方法。首先,寫一個POJO類,代碼如下:
package rong.propertyUtils;


public class Entity
{
private Integer id = 5;
private String name = "rongxinhua";

public Integer getId()
{
return id;
}

public void setId(Integer id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String haha()
{
return "Ha,Ha";
}

public void sayHelle(String name)
{
System.out.println(name + " say, Hello!");
}

public String countAges(int x, int y)
{
return "My Age is " + (x + y);
}
}

接著寫一個測試的類,代碼如下:
package rong.propertyUtils;

import java.util.Map;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;


public class TestPropertyUtils
{

public static void main(String[] args) throws Exception
{
Entity entity = new Entity();
//通過PropertyUtils的getProperty方法獲取指定屬性的值
Integer id = (Integer)PropertyUtils.getProperty(entity, "id");
String name = (String)PropertyUtils.getProperty(entity, "name");
System.out.println("id = " + id + " name = " + name);
//調用PropertyUtils的setProperty方法設置entity的指定屬性
PropertyUtils.setProperty(entity, "name", "心夢帆影");
System.out.println("name = " + entity.getName());
//通過PropertyUtils的describe方法把entity的所有屬性與屬性值封裝進Map中
Map map = PropertyUtils.describe(entity);
System.out.println("id = " + map.get("id") + " name = " + map.get("name"));
//通過MethodUtils的invokeMethod方法,執行指定的entity中的方法(無參的情況)
System.out.println( MethodUtils.invokeMethod(entity, "haha", null) );
//通過MethodUtils的invokeMethod方法,執行指定的entity中的方法(1參的情況)
MethodUtils.invokeMethod(entity, "sayHelle", "心夢帆影");
//通過MethodUtils的invokeMethod方法,執行指定的entity中的方法(多參的情況)

Object[] params = new Object[]
{new Integer(10),new Integer(12)};
String msg = (String)MethodUtils.invokeMethod(entity, "countAges", params);
System.out.println(msg);
}

}

執行結果如下:
id = 5 name = rongxinhua
name = 心夢帆影
id = 5 name = 心夢帆影
Ha,Ha
心夢帆影 say, Hello!
My Age is 22
本文原創,轉載請注明出處,謝謝!http://m.tkk7.com/rongxh7(心夢帆影JavaEE技術博客)
posted on 2009-06-22 14:39
心夢帆影 閱讀(8890)
評論(2) 編輯 收藏 所屬分類:
JavaSE