jakarta ee使用Java反射从对象列表中查找参数之和
我有一张物品清单
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对象发生变化时记得更新这些代码。。。。所以我的想法是,我将使用反射来获得所有可以从数字中赋值的字段,并对它们求和,但是我如何进行实际的加法呢
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);
}
}
# 1 楼答案
是的,有:
# 2 楼答案
可以使用BeanUtils而不是直接反射API。使用BeanUtils,确保您的类符合JavaBean规则,并使用
public static Map describe(Object bean)
获取给定bean上可用的属性列表一旦你得到了属性的名称,你就可以通过使用
public static String getProperty(Object bean, String name)
得到一个独立的值,然后把它加起来