PropertyUtils,MethodUtils使用

本文介绍Apache Commons BeanUtils和MethodUtils的使用方法,通过示例演示如何利用这两个工具类进行属性操作及方法调用。具体包括属性读取、设置、复制到Map,以及对象方法的调用等。

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"   );
//	}	
	
	
}

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值