问题来源:一个表中有将近20个字段,现在需要按照指定的时间范围来汇总每个字段,并把汇总的结果放在与此表对应的实体对象中返回。业务逻辑非常简单,就是在编码时需要一个一个属性的赋值,有些繁琐,此代码长度过长。
解决方法:使用循环,先取得每个属性的set方法,再使用反射来调用set方法赋值
代码如下:
public TomEnsure getTomEnsureStatis(String startDate,String endDate){
TomEnsure tomEnsure = new TomEnsure();
SqlRowSet result = null;
int sumNumber = 0;
//先得出各汇总字段
String[] colStr = {"scheduled_task","special_task","chartered_task","other_task",
"military_task","amount_task","domestic_task","area_task","internation_task",
"passenger_task","manned_task","other_type_task","nonprofit_task",
"amount_general_task","total_task"};
for (String str : colStr){
String sql = "select sum(" + str + ")"
+ " as sumNumber from t_tom_ensure_statis where statis_day between '"
+ startDate + "' and '" + endDate + "'";
result = statisticDataJdbcTemplate.queryForRowSet(sql);
sumNumber = result.next() ? result.getInt("sumNumber") : 0;
try {
Method[] m = tomEnsure.getClass().getMethods();
for (int i = 0; i < m.length; i++ ){
if (("set" + str.replace("_","")).toLowerCase().equals(m[i].getName().toLowerCase())){
m[i].invoke(tomEnsure,sumNumber); //反射赋值
break;
}
}
}catch (Exception e){
log.error(e.getMessage());
}
}
return tomEnsure;
}
网友评论