/** * * 函数名称:getTotalAndAvg * 功能说明:对传入的对象集合的指定属性作合计和求平均值 * 参数说明:参数类型 list ------ 要做合计的对象集合 * * 返回类型:BigDecimal[] ------ 返回页面的值 * 作 者:douzaixing * 修 改 者:douzaixing * */ public static BigDecimal[] getTotalAndAvg(List list) { try { int paramCount = 0; Object o = list.get(0); Object dto = o.getClass().newInstance(); Field[] names = o.getClass().getDeclaredFields(); Field f = null; for (int i = 0; i < names.length; i++) { f = names; String type = f.getType().toString(); // System.out.println("type:" + type); if (type.equals("class java.math.BigDecimal")) { paramCount++; } } // System.out.println("paramCount:" + paramCount); BigDecimal[] num = new BigDecimal[paramCount * 2]; BigDecimal[] count = new BigDecimal[paramCount]; for (int i = 0; i < paramCount; i++) { num = BigDecimal.ZERO; count = BigDecimal.ZERO; } for (ListIterator li = list.listIterator(); li.hasNext();) { Object obj = li.next(); if (obj != null) { dto = o.getClass().cast(obj); for (int i = 0, j = 0; i < names.length; i++) { f = names; String type = f.getType().toString(); if (type.equals("class java.math.BigDecimal")) { String name = f.getName(); // System.out.println("name:"+name); String MName = "get"+name.substring(0,1).toUpperCase()+name.substring(1); Method m = o.getClass().getMethod(MName, null); BigDecimal value = (BigDecimal) m.invoke(dto, null); // System.out.println("value:"+value); if (value != null) { num[j] = num[j].add(value); count[j] = count[j].add(BigDecimal.ONE); } if (j < paramCount) { j++; // System.out.println(j); } if (j >= paramCount) { j = 0; } } } for (int i = 0; i < num.length / 2; i++) { num = BigDecimal.ZERO; if (count.intValue() != 0) { num = num.divide(count, 5, BigDecimal.ROUND_HALF_UP); } } } } return num; } catch (Exception e) { e.printStackTrace(); } return null; }