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[] {}));
		}
	}

}

發佈了150 篇原創文章 · 獲贊 7 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章