假設有一個類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[] {}));
}
}
}