使用Java Reflection从对象列表中查找参数总和

时间:2013-06-14 04:07:21

标签: java java-ee reflection

我有一个项目清单......

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

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

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

获得属性名称后,您可以使用public static String getProperty(Object bean, String name)获得个人价值并将其全部加起来