Searcher
								2015-05-03 16:00:09
							
							java bean 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[] {}));
		}
	}
}
由最代码官方编辑于2015-5-4 22:16:28
猜你喜欢
请下载代码后再发表评论
     相关代码
相关代码
				 最近下载
最近下载
				 最近浏览
最近浏览
				
                wangdongkui     LV1
                2020年3月28日
            
            
        
                luohaipeng     LV23
                2019年12月6日
            
            
        
                15000155586     LV2
                2018年12月20日
            
            
        
                wkc     LV21
                2018年5月14日
            
            
        
                2602275348     LV12
                2018年3月21日
            
            
        
                zr_duanyi     LV4
                2018年1月23日
            
            
        
                sunboris514     LV8
                2018年1月4日
            
            
        
                chenwch     LV8
                2017年12月24日
            
            
        
                dagap8     LV1
                2017年12月15日
            
            
        
                kevindel     LV15
                2017年2月7日
            
            
        




 
     
                 
                