Tom Tucker
Tom Tucker

Reputation: 11916

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?

Upvotes: 9

Views: 2748

Answers (4)

user207421
user207421

Reputation: 310998

This is a job for the Visitor pattern.

Upvotes: 3

Keith Randall
Keith Randall

Reputation: 23265

I'm not sure you want an answer to this question. You're interested in setting up a situation where

test((String)x)

does not do the same thing as

test((Object)x)

For x which are Strings. This is a Bad Idea™ and will just lead to lots of confusion. Use a different method name if you really want different behavior.

Just make test(Object x) dispatch to test(String x) if x is a String, then you don't need to worry about which test method gets called.

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86774

Overloaded method resolution happens at compile time in Java. You'll have to do the resolution yourself (a switch, if-then-else ladder or table-lookup), or find a different pattern that can be implemented in Java.

Upvotes: 1

Jason S
Jason S

Reputation: 189776

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);
}

Upvotes: 6

Related Questions