我有一个物品清单...
public class Item implements Serializable {
private Double subTotalCash;
private Double subTotalCredit;
private Double totalShipping;
private Double grandTotal;
private Integer countSubItems;
private Integer countSomethingElse;
private Integer countMoreThingsNotListedHere;
...
// getters and setters here
}
所有重要的参数都是 Double、Integer、Float 或 Long(都是扩展数字)我想要做的是将每个参数相加并将它们汇总到一个“主”项中。
Item masterItem = new Item();
for(Item item:items) {
addValuesFromItemToMaster(item, master);
}
如果它只有十几个值,那没什么大不了的,但是我们正在谈论一堆参数,它们变化得足够频繁,以至于我不想记住在 Item 对象时更新此代码变化....所以我的想法是我会使用反射来获取所有可从 Number 分配的字段并对它们求和,但我该如何进行实际的加法?
private void addValuesFromItemToMaster(Item child, Item master) throws Exception {
if(child == null || master == null) return;
Field[] objectFields = master.getClass().getDeclaredFields();
for (Field field : objectFields) {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue; // don't add any static fields
if(!Number.class.isAssignableFrom(field.getType())) continue; // If this is not a numeric field
if(field.getType() == AtomicInteger.class || field.getType() == AtomicLong.class || field.getType() == Byte.class || field.getType() == BigInteger.class) continue;
Number childValue = (Number)PropertyUtils.getProperty(child, field.getName());
Number masterValue = (Number)PropertyUtils.getProperty(master, field.getName());
if(childValue == null) continue;
if(masterValue == null) masterValue = childValue;
// is there something I can put here to get the masterValue += childValue?
// is there a way to cast to the field.getType()?
BeanUtils.setProperty(master, field.getName(), n);
}
}