Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dynamic overload resolution possible in Java?

So I have a class of overloaded methods like this:

class Foo {
    public void test(Object value) {
        ...
    }

    public void test(String value) {
        ...
    }
}

I need to pass a property value of a bean to one of these methods depending on its type, but I don't know the actual property type until the runtime. e.g.

public void run(Object bean, String propertyName) {
    Foo foo = new Foo();
    foo.test(PropertyUtils.getProperty(bean, propertyName));
}

BTW, PropertyUtils.getProperty() is a helper method that returns a value of the specified property on a bean. PropertyUtils.getProperty() returns an Object, so that test(Object value) will be always called and the actual property type will be ignored.

I can figure out the propery type in the runtime, even if its value is null. Is there such a thing as dynamic casting in Java? If not, is there a way to have an overloaded method with the correct parameter type called?

like image 733
Tom Tucker Avatar asked Dec 24 '10 02:12

Tom Tucker


People also ask

What is overload resolution in Java?

Here is what I know about overload resolution in java: The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done).

Why method overloading is not possible by changing the return type in Java?

Q) Why Method Overloading is not possible by changing the return type of method only? In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Can overload have different return types?

Yes. It is possible for overridden methods to have different return type . But the limitations are that the overridden method must have a return type that is more specific type of the return type of the actual method.

Can overloaded methods have different return types Java?

No, you cannot overload a method based on different return type but same argument type and number in java.


1 Answers

Overriding is what has dynamic binding in Java. Overloading has static binding, and which function is called is determined at compile time, not at runtime. See this SO question.

Therefore you can't use overloading for run time selection of methods. Suggest you use one of the other OOP design patterns in java, or at least instanceof:

public void dispatch(Object o)
{
   if (o instanceof String)
       handleString((String)o);
   else if (o instanceof File)
       handleFile((File)o);
   else
       handleObject(o);
}
like image 75
Jason S Avatar answered Nov 15 '22 20:11

Jason S