我有一个项目列表...
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
}
所有重要的参数都是双精度、整数、浮点数或长整型(所有扩展数字(我想做的是将每个参数相加并将它们合计到一个"主"项目中。
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);
}
}
// 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);
}
您可以使用 BeanUtils 而不是直接反射 API。使用 BeanUtils,确保您的类符合 JavaBean 规则,并使用 public static Map describe(Object bean)
获取给定 Bean 上可用的属性列表。
获得属性名称后,您可以使用public static String getProperty(Object bean, String name)
获取单独的值并将其全部汇总