There are two issues associated with casting of types in the Java bindings. The simplest is the casting of SIDL objects implemented in Java. The second involves the casting of SIDL interfaces which, as discussed in Subsection 10.2.3, is a little more involved. This subsection describes the normal, object casting process before that of the Java equivalents of SIDL interfaces.
In some cases it is necessary to cast the internal representation of
an object as well as the Java object. (For example, getting an object
from a SIDL array of superclass objects.) In these cases a Java cast is
insufficient. Therefore two built-in casting functions have
been provided _cast() and _cast2().
The static _cast(object) function returns a new
Java object based on the object argument. For example,
foo.bar newobj = (foo.bar) foo.bar._cast(oldobj) will cast
oldobj, an object of type sidl.BaseClass, to
foo.bar. If this is an invalid cast, _cast will
return null.
The _cast2(``ClassName'') method, on the other hand, casts an object to a named type (i.e., ClassName). It performs basically the same function as _cast, but the form is object._cast2(``ClassName''), where ClassName must be a fully qualified name. If the cast is invalid, or a class of that name cannot be found, null is returned.
Both functions return a sidl.BaseClass which must then be Java casted to the correct Java class type. They both also create a new Java object that owns a new reference to the IOR object. Although you never have to worry about reference counting in Java, it is important to remember that casting leaves two valid objects.
As mentioned in Subsection 10.2.3, SIDL interfaces are mapped
to wrapper classes that inherit from an interface. As a result, they
can be Java cast to their ancestor interfaces but must be Babel cast to
any classes. In the following example, Subclass implements
SuperInterface
SuperInterface.Array1 arry = new SuperInterface.Array1(5, true); SubClass obj = new SubClass(); arry.set(0, (SuperInterface)obj); obj = null; SuperInterface temp = arry.get(0); obj = (SubClass) temp; //INCORRECT Will throw ClassCastException obj = (SubClass) SubClass._cast((SuperInterface.Wrapper)temp); //CORRECT
Finally, in some cases, as when the interface is retrieved from an array, Java
casting the interface is not necessary before Babel casting it; however,
that is not true in general.
The following is an example of casting an interface in a Java implementation
public objarg.SubClass toClass_Impl (/*in*/ objarg.Iface ifcy ) { // DO-NOT-DELETE splicer.begin(objarg.SubClass.toClass) objarg.SubClass ret = (objarg.SubClass) ((objarg.Iface.Wrapper)ifcy)._cast2("objarg.SubClass"); return ret; // DO-NOT-DELETE splicer.end(objarg.SubClass.toClass) }