1 PropertyUtils
1 )这个类可以对属性设值,与取出属性的值
2 ) 可已经对象属性,完全拷贝到另一个Map中
2 MethodUtils
可以调用一些对象的方法
测试方法:
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, "sayHello", null) );
//通过MethodUtils的invokeMethod方法,执行指定的entity中的方法(1参的情况)
MethodUtils.invokeMethod(entity, "sayHello1", "心梦帆影");
//通过MethodUtils的invokeMethod方法,执行指定的entity中的方法(多参的情况)
// Object[] params1 = new Object[]{new Integer(10),new Integer(12)};
// String msg = (String)MethodUtils.invokeMethod(entity, "countAges", params1);
// System.out.println(msg);
//通过MethodUtils的invokeMethod方法,执行指定的entity中的方法(多参的情况)
// Integer[] params ={1,2};
// MethodUtils.invokeMethod(entity, "sayHello2", params);
}
}
测试实体类
package test2;
public class Entity {
private Integer id;
private String name;
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 void sayHello( ){
System.out.println("执行了 sayHello == 0" );
}
public void sayHello1(String word ){
System.out.println("执行了 sayHello ==1 " +word );
}
// public String countAges(Object[] w){
// System.out.println( "44444444");
// return "44444444444";
// }
//
// public void sayHello2( Integer[] w){
// System.out.println("执行了 sayHello == 2" );
// }
}
本文介绍Apache Commons BeanUtils和MethodUtils的使用方法,通过示例演示如何利用这两个工具类进行属性操作及方法调用。具体包括属性读取、设置、复制到Map,以及对象方法的调用等。
1192

被折叠的 条评论
为什么被折叠?



