现在的位置: 首页 > 综合 > 正文

JAVA反射机制的应用

2013年08月09日 ⁄ 综合 ⁄ 共 2232字 ⁄ 字号 评论关闭

这是通过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.      }

抱歉!评论已关闭.