Actually, this is far more complex than I assumed because you cannot do arithmetic on a Number object...
Hmm... There is certainly a messy way of doing this, but I do not know if there is a generic way of doing this.
The messy way of doing it would be something like:
public <T extends Number> T add(T val1, T val2) {
if(val1 instanceof Integer) {
return (T)new Integer((Integer)val1 + (Integer)val2);
}
else if(val1 instanceof Double) {
return (T)new Double((Double)val1 + (Double)val2);
}
// And follow this pattern for every Number type
}
It is not ideal. Maybe someone else has a better idea.