用反射写的求和平均值

/**
   *
    * 函数名称: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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

窦再兴

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值