I am using the JCR API that uses method overloading like so:
setProperty(String value)
setProperty(Boolean value)
setProperty(Integer value)
...
I then have a Collection<Object> which may contain String, Boolean, Integer, etc. instances.
I would like to iterate over this collection, passing each element to the correct setProperty implementation for that instance type. The obvious way is something like 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 – and deviating from OO ideals – this solution simply doesn’t scale. While it works for this particular case, it would quickly become unwieldy as the number of types grows.
I really feel as though there must be some elegant trick or util for automatically performing this casting operation.
No, there isn’t – because you’re asking for overload resolution, which is normally performed at compile-time, to be performed at execution time instead.
Options: