Java – How to call addition operator on two objects

javaobjectpolymorphism

In java, I have two Objects that addition (+) is supported on them, for example two ints or two Strings. 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 Objects, 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:

public Object add(Object op1, Object op2){

    if( op1 instanceof String || op2 instanceof String){
        return String.valueOf(op1) + String.valueOf(op2);
    }

    if( !(op1 instanceof Number) || !(op2 instanceof Number) ){
        throw new Exception(“invalid operands for mathematical operator [+]”);
    }

    if(op1 instanceof Double || op2 instanceof Double){
        return ((Number)op1).doubleValue() + ((Number)op2).doubleValue();
    }

    if(op1 instanceof Float || op2 instanceof Float){
        return ((Number)op1).floatValue() + ((Number)op2).floatValue();
    }

    if(op1 instanceof Long || op2 instanceof Long){
        return ((Number)op1).longValue() + ((Number)op2).longValue();
    }

    return ((Number)op1).intValue() + ((Number)op2).intValue();
}

And in theory you can call this method with numerical reference types, numerical primitive types, and even Strings.