Is Dynamic Casting Possible in Java
Posted
by
Tom Tucker
on Stack Overflow
See other posts from Stack Overflow
or by Tom Tucker
Published on 2010-12-24T02:36:29Z
Indexed on
2010/12/24
2:54 UTC
Read the original article
Hit count: 267
java
|reflection
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?
© Stack Overflow or respective owner