您的位置:首页 > 其它

一个反射方法应用实例

2018-01-05 15:16 337 查看

需求:在导出的时候,需要将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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射