0

我有一个物品清单...

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);
    }
}
4

2 回答 2

3
// is there something I can put here to get the masterValue += childValue?
// is there a way to cast to the field.getType()?
// setMethod.invoke(master, newValueGoesHere);

就在这里:

if (field.getType() == Integer.TYPE || field.getType() == Integer.class) {
    Integer i = masterValue.intValue() + childValue.intValue();
    setMethod.invoke(master, i);
} else if (field.getType() == Long.TYPE || field.getType() == Long.class) {
    Long l = masterValue.longValue() + childValue.longValue();
    setMethod.invoke(master, l);
} else if (field.getType() == Float.TYPE || field.getType() == Float.class) {
    Float f = masterValue.floatValue() + childValue.floatValue();
    setMethod.invoke(master, f);
} else if (field.getType() == Double.TYPE || field.getType() == Double.class) {
    Double d = masterValue.doubleValue() + childValue.doubleValue();
    setMethod.invoke(master, d);
}
于 2013-06-14T04:24:43.367 回答
1

您可以使用BeanUtils而不是直接反射 API。使用 BeanUtils,确保您的类符合 JavaBean 规则,并用于public static Map describe(Object bean)获取给定 bean 上可用的属性列表。

public static String getProperty(Object bean, String name)一旦你得到了属性的名称,你可以通过使用和总结得到单独的价值

于 2013-06-14T04:24:05.240 回答