JAVA反射机制的应用

这是通过java的反射机制可以避免重复的写相似的调用方法
  1. // 通过反射方法set数据
  2.                 for (int i = 0; i < GRADE_NUM; i++) {
  3.                     method1 = GetValueMethod.setMethod(new FR0313Dto(),
  4.                             "minorityStuNum" + (i + 1),
  5.                             new Class[] { String.class });
  6.                     method2 = GetValueMethod.setMethod(new FR0313Dto(),
  7.                             "girlStuNum" + (i + 1),
  8.                             new Class[] { String.class });
  9.                     method3 = GetValueMethod.setMethod(new FR0313Dto(),
  10.                             "stuNum" + (i + 1), new Class[] { String.class });
  11.                     try {
  12.                         method1.invoke(dto, new Object[] { String
  13.                                 .valueOf(minorityStuNum) });
  14.                         method2.invoke(dto, new Object[] { String
  15.                                 .valueOf(getIntValue(acadGirlMap
  16.                                         .get(gradeAcadyear[i]))) });
  17.                         method3.invoke(dto, new Object[] { String
  18.                                 .valueOf(getIntValue(acadStuMap
  19.                                         .get(gradeAcadyear[i]))) });
  20.                     } catch (IllegalArgumentException e) {
  21.                         log.error(e);
  22.                     } catch (IllegalAccessException e) {
  23.                         log.error(e);
  24.                     } catch (InvocationTargetException e) {
  25.                         log.error(e);
  26.                     }
  27.                 }

下面是拼装set方法,GetValueMethod中的setMethod

  1.  public static Method setMethod(Object object, String propertyName,
  2.                 Class[] partypes) {
  3.          if (propertyName == null || propertyName.length() == 0) {
  4.                 return null;
  5.             }
  6.          String propertyNameUpper = propertyName.substring(01).toUpperCase()
  7.             + propertyName.substring(1);
  8.          
  9.          String methodName = "set" + propertyNameUpper;
  10.             Method method = null;
  11.             try {
  12.                 method = object.getClass().getMethod(methodName, partypes);
  13.             } catch (SecurityException e) {
  14.                 e.printStackTrace();
  15.             } catch (NoSuchMethodException e) {
  16.                 e.printStackTrace();
  17.             }
  18.             return method;
  19.      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值