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?
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).
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.
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.
No, you cannot overload a method based on different return type but same argument type and number in java.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With