PropertyDescriptor的使用

来源:互联网 发布:nginx http2.0 配置 编辑:程序博客网 时间:2024/06/04 18:08

假设有一个类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[] {}));}}}

0 0