java - How can I automatically cast an Object reference to the instance type? -
i using jcr api uses method overloading so:
setproperty(string value) setproperty(boolean value) setproperty(integer value) ... i have collection<object> may contain string, boolean, integer, etc. instances.
i iterate on collection, passing each element correct setproperty implementation instance type. obvious way this:
for (object value : values) { if (value instanceof string) node.setproperty((string) value); if (value instanceof boolean) node.setproperty((boolean) value); if (value instanceof integer) node.setproperty((integer) value); ... } now besides being ugly - , deviating oo ideals - solution doesn't scale. while works particular case, become unwieldy number of types grows.
i feel though there must elegant trick or util automatically performing casting operation.
no, there isn't - because you're asking overload resolution, performed @ compile-time, performed @ execution time instead.
options:
- use reflection find , execute method
- use visitor pattern emulate double dispatch (this may not appropriate case; i'm not fond of visitor pattern many others are)
Comments
Post a Comment