PropertyDescriptor的使用

假设有一个类Manager,有属性je01、je02........je30,给这些属性设值的一般做法是:

Manager man = new Manager();
man.setJe01("1");
man.setJe02("b");
............
man.setJe29("29");
man.setJe30("30");
使用PropertyDescriptor可以大大简化代码,
public class Manager {
	private int je01;
	....
	private int je30;
	
	public int getJe01() {
		return je01;
	}
	public void setJe01(int je01) {
		this.je01 = je01;
	}
	
	......
	
	public int getJe30() {
		return je30;
	}
	public void setJe30(int je30) {
		this.je30 = je30;
	}

}


测试:

public class TestPropertyDescriptor {

	public static void main(String[] args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		Manager man = new Manager();
		for(int i = 1; i <= 30; i++) {
			// 拼接Manager属性
			String propertyName = "je" + (i < 10 ? "0" + i : (i < 20 ? i : (i < 30 ? i : "30")));
			// 取得PropertyDescriptor实例
			PropertyDescriptor pd = new PropertyDescriptor(propertyName, man.getClass());
			// 取得Manager的set方法
			Method method = pd.getWriteMethod();
			// 设值
			method.invoke(man, (int)Math.round((Math.random()*1000)));
		}
		for(int i = 1; i <= 30; ++i) {
			String propertyName = "je" + (i < 10 ? "0" + i : (i < 20 ? i : (i < 30 ? i : "30")));
			PropertyDescriptor pd = new PropertyDescriptor(propertyName, man.getClass());
			// 取得Manager的get方法
			Method method = pd.getReadMethod();
			// 输出属性值
			System.out.println(method.invoke(man, new Object[] {}));
		}
	}

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值