1. 程式人生 > >一個反射方法應用例項

一個反射方法應用例項

需求:在匯出的時候,需要將list中的物件值賦給陣列物件,返回一個數組集合

  • 原先的程式碼,在每一個匯出的方法下需要寫一個這樣的轉換方法
private List<Object> transBean2ObjectGradeNumber(List<GradeNumberOfPeopleStatistical> list) {
        List<Object> retList = new ArrayList<Object>();
        if (list == null || list.isEmpty()) {
            Object[] objs = new
Object[6]; retList.add(objs); return retList; } Object[] objs = null; for (GradeNumberOfPeopleStatistical temp : list) { objs = new Object[6]; int index = 0; objs[index++] = temp.getGradeTypeName(); objs[index
++] = temp.getTotalClass(); objs[index++] = temp.getMen(); objs[index++] = temp.getWomen(); objs[index++] = temp.getMenWomenProportion(); objs[index++] = temp.getTotalPeople(); retList.add(objs); } return retList; }
  • 新的運用反射的方法,該方法為公共的方法
private List<Object> transBean2ObjectExport(List<?> list,String[] methodNames) throws Exception {
        List<Object> retList = new ArrayList<Object>();
        if (list == null || list.isEmpty()) {
            Object[] objs = new Object[methodNames.length];
            retList.add(objs);
            return retList;
        }
        Object[] objs = null;

        for (Object object : list) {
            objs = new Object[methodNames.length];
            Class<? extends Object> cls = object.getClass();
            for (int i = 0; i <  methodNames.length ; i++ ) {
                Method method = cls.getMethod("get" + methodNames[i].substring(0,1).toUpperCase() + methodNames[i].substring(1));
                objs[i] = method.invoke(object);
            }
            retList.add(objs);

        }
        return retList;
    }