开发者

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 ideal开发者_如何学Pythons - 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 (i.e. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜