Category: Proxy usage


How do I cast a proxy object to another proxy type?


You have to use the dyna_cast() method, not to be confused with the C++ dynamic_cast operator. It's useful to understand why we designed the framework like this.

Let's take a look at a typical Java method, for example the Hashtable class' put() method. It is declared as follows:

Object      put( Object key, Object value ); 

The corresponding C++ method looks like this (some framework arguments omitted for clarity):

java::lang::Object      put( const java::lang::Object & key, 
                             const java::lang::Object & value ); 

The part you need to focus on is the return type. The put() method returns the previously registered value for the given key. This will so often be a null reference that most applications completely disregard it. This common usage pattern of disregarding return values forced us to return results by value. We return on instance of type Object on the stack; not a pointer to, not a reference to, but a real Object instance. This is the only feasible way to make sure that the Java object represented by the C++ instance is cleaned up automatically when the programmer ignores the return value.

This design has a consequence in the area of type casts. The returned object really is of type Object, it's not of a different type and just refered to as an Object. You cannot cast it to another type because it isn't of another type! So how do you write code corresponding to the following Java snippet?


String      oldvalue = (String)ht.put( "key", "newvalue" ); 

In the above snippet, you are using your expert knowledge about the application (in this case your knowledge that there are only String values in the Hashtable) to classcast the return value to the proper type. In C++, you won't be able to do that because the returned C++ object really is an Object and not a String. The returned Java object is a String, but it is wrapped in a proxy Object instance.

To help you out with this problem, we supply a static method that allows you to "rewrap" a Java object reference in an instance of a different proxy type. The method is called dyna_cast() and checks at runtime that the Java instance represented by the C++ object is type-compatible with the target C++ proxy type. The above Java snippet would be written as:


String      oldvalue = String::dyna_cast( 
                           ht.put( "key", "newvalue" ) ); 



Copyright 2006-2011 by Codemesh, Inc., ALL RIGHTS RESERVED

frequently asked questions
home products support customers partners newsroom about us contact us