Casting a proxy to the most derived interface

in Help Center
I have an hierarchy of interfaces:
Now, if there was a method which cast a proxy to its actual type, I could write
I could write it using reflection (error checking omitted):
interface I1 {...} interface I2 extends I1 {...} interface I3 extends I1 {...}and I need to do something with a proxy which depends on the type of object (not the static type). That is,
ObjectPrx prx = ... I1Prx i1 = I1PrxHelper.checkedCast(prx); if (i1 != null) then ... I2Prx i2 = I2PrxHelper.checkedCast(prx); if (i2 != null) ... I3Prx i1 = I3PrxHelper.checkedCast(prx); if (i3 != null) ...However, the above requires a lot of remote calls and 2 more will be added each time a new interface is introduced.
Now, if there was a method which cast a proxy to its actual type, I could write
ObjectPrx precisePrx = castToActualType(prx); if (precisePrx instanceOf I1Prx) ... if (precisePrx instanceOf I2Prx) ... if (precisePrx instanceOf I3Prx) ...
I could write it using reflection (error checking omitted):
ObjectPrx castToActualType(ObjectPrx prx) { String type_id = prx.ice_id(); String prxInterfaceName = type_id.substring(2).replaceAll("::", ".") ++ "Prx"; String helperName = prxInterfaceName ++ "Helper"; Class<?> klass = Class.forName(helperName); Method castMethod = klass.getMethod("checkedCast"); return (ObjectPrx) castMethod.invoke(null, prx); }Is there a simpler way to do it? Or an explanation why this is a bad idea?
0
Comments
I would go with the following option:
Note that it's a bit unfortunate that you have to use the generated _<interface name>Disp type here to get the type ID, it would be nicer if ice_staticId() was a static operation of the PrxHelper class, we'll discuss adding this.
One issue with your solution that uses reflection is that it assumes that the Slice type ID maps to an equivalent Java class name. This might not always be the case if the [noparse]"java:package:com.foo"[/noparse] metadata is used in the Slice to generate the Java classes in a given package.
Cheers,
Benoit.
That being said, such checks usually indicate that you're not taking advantage of polymorphism. Why are you checking for the type of the proxies? Is it to call some specific methods on the proxies afterwards? Perhaps you can add a method on the base interface to simplify this code?
Cheers,
Benoit.
This way, you can retrieve all the properties with a single request and you can check for the type of the result of getInfo() to display the properties of each object:
Cheers,
Benoit.
Cheers,
Benoit.