将数据对象加和到一起

165 阅读1分钟

将多个bean对象多个属性,相同的属性数据统计到一起

目前只支持 处理Integer数据对象,单个或者量少推荐使用jdk8特性

public static <T> T combineBeans(List<T> list) throws BusinessException {
	T ret = null;
	try {
		if (ObjectUtils.isEmpty(list)) {
			return null;
		}
		Class sourceBeanClass = list.get(0).getClass();
		Object newInstance = sourceBeanClass.newInstance();
		Field[] fields = sourceBeanClass.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			if (Modifier.isStatic(field.getModifiers())) {
				continue;
			}
			field.setAccessible(true);
			/**
			 * 处理integer数据对象
			 */
			if (field.getType() == Integer.class) {
				Integer sumI = 0;
				for (T valObject : list) {
					Object num = field.get(valObject);
					Integer numI = (Integer) (num == null ? 0 : num);
					sumI += numI;
				}
				field.set(newInstance, sumI);
			}
		}
		ret = (T) sourceBeanClass.cast(newInstance);
	} catch (Exception e) {
		e.printStackTrace();
		throw new BusinessException("数据处理异常");
	}
	return ret;
}

参考资料: www.cnblogs.com/nongzihong/…