这是通过java的反射机制可以避免重复的写相似的调用方法
- // 通过反射方法set数据
- for (int i = 0; i < GRADE_NUM; i++) {
- method1 = GetValueMethod.setMethod(new FR0313Dto(),
- "minorityStuNum" + (i + 1),
- new Class[] { String.class });
- method2 = GetValueMethod.setMethod(new FR0313Dto(),
- "girlStuNum" + (i + 1),
- new Class[] { String.class });
- method3 = GetValueMethod.setMethod(new FR0313Dto(),
- "stuNum" + (i + 1), new Class[] { String.class });
- try {
- method1.invoke(dto, new Object[] { String
- .valueOf(minorityStuNum) });
- method2.invoke(dto, new Object[] { String
- .valueOf(getIntValue(acadGirlMap
- .get(gradeAcadyear[i]))) });
- method3.invoke(dto, new Object[] { String
- .valueOf(getIntValue(acadStuMap
- .get(gradeAcadyear[i]))) });
- } catch (IllegalArgumentException e) {
- log.error(e);
- } catch (IllegalAccessException e) {
- log.error(e);
- } catch (InvocationTargetException e) {
- log.error(e);
- }
- }
下面是拼装set方法,GetValueMethod中的setMethod
- public static Method setMethod(Object object, String propertyName,
- Class[] partypes) {
- if (propertyName == null || propertyName.length() == 0) {
- return null;
- }
- String propertyNameUpper = propertyName.substring(0, 1).toUpperCase()
- + propertyName.substring(1);
- String methodName = "set" + propertyNameUpper;
- Method method = null;
- try {
- method = object.getClass().getMethod(methodName, partypes);
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- }
- return method;
- }