简体   繁体   中英

How can I automatically cast an Object reference to the instance type?

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:

  • Use reflection to find and execute the method
  • Use the visitor pattern to emulate double dispatch (this may not be appropriate for your case; I'm not as fond of the visitor pattern as many others are)

I really feel as though there must be some elegant trick or util for automatically performing this casting operation.

I don't think you will find one.

If you had a large number of type alternatives (ie 20 or more), it might make sense to do a hash table lookup on value.getClass() to give you a instance of some "setter" object. But you'd need to write a lot of boilerplate code ... so that doesn't count as elegant, IMO.

Reflection is also an option, but its expensive and introduces more potential runtime failure modes. Besides, I don't actually see how it would help much in this particular case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM