In java, I have two Object
s that addition (+) is supported on them, for example two int
s or two String
s. How I can write a function to really add them without specifying the types?
note: I don't want something like C++ function templates, as two operands are just Object
s, i.e. I want to implement a function add
:
Object add(Object a, Object b){
// ?
}
and then be able to do something like this:
Object a = 1, b = 2;
Object c = add(a, b);
Best Answer
I too require something similar so I slapped together something which hopefully returns the same type as the built-in addition operator would return (except upcasted to Object). I used the java spec to figure out the rules of type conversion, particular section 5.6.2 Binary Numeric Promotion. I haven't tested this yet:
And in theory you can call this method with numerical reference types, numerical primitive types, and even Strings.