数字相加通用泛型方法
/**
* 通用数字相加 支持 Long,Integer,Double,Float,BigDecimal 类型必须一致
* @param values
* @param <T>
* @return
*/
public static <T extends Number> T addNumber(T... values){
BigDecimal sumValue = BigDecimal.ZERO;
T firstValue = null;
for(T v : values){
if(v!=null){
if(firstValue == null){
firstValue = v;
}
if(v instanceof Long) {
sumValue = sumValue.add(BigDecimal.valueOf(v.longValue()));
}
if(v instanceof Float){
sumValue = sumValue.add(BigDecimal.valueOf(v.floatValue()));
}
if(v instanceof Integer){
sumValue = sumValue.add(BigDecimal.valueOf(v.intValue()));
}
if(v instanceof Double){
sumValue = sumValue.add(BigDecimal.valueOf(v.doubleValue()));
}
if(v instanceof BigDecimal){
sumValue = sumValue.add((BigDecimal) v);
}
}
}
if(firstValue instanceof Long) {
return (T)((Long) sumValue.longValue());
}
if(firstValue instanceof Float){
return (T)((Float) sumValue.floatValue());
}
if(firstValue instanceof Integer){
return (T)((Integer) sumValue.intValue());
}
if(firstValue instanceof Double){
return (T)((Double) sumValue.doubleValue());
}
if(firstValue instanceof BigDecimal){
return (T) sumValue;
}
return null;
}