2005/5/10

     
 

Casting

artefaktur

| References | Casting | Arrays | Import | instanceof | Package | Synchronization | Throwable | finally | Dangerous | Stack | String |

How to use casting in ACDK with several differences compared to Java.

Content of this chapter:

   DownCast
   instanceof
   Upcast
   C++-Objects
     Pointer
     C++ references
   Casting Arrays

 DownCast

In Java, you can test if an Object is a given Class:

// Java 
void foo(Object object)
{
  try {
    String astr = (String)object;
  } catch (BadCastException ex) {
    // Oops
  }
}

The same idiom can be used in ACDK, yet with a little modified semantic:

// C++ / acdk
void foo(RObject object)
{
  try {
    RString astr = (RString)object;
  } catch (RBadCastException ex) {
    // Oops
  }
}

 instanceof

You can use  instanceof to test if a given object is type of Class. Sample:

 Upcast

To cast from derived class to an base class, you can also use the explicit cast construction described above, but it is not recomended, because is has more runtime overhead (performance), no compile time type checking available and you have to type more text. Simple use the & operator to upcast reference:

  void foo(RObject obj)
  {
    // does something
  }
  RStringBuffer sb = new StringBuffer("asdf");
  foo((RObject)sb); // don't use this, although it works
  foo(&sb); // use this, because better performance

 C++-Objects

 Pointer

Casting ACDK objects to C++ object pointer:

RStringBuffer sb = new StringBuffer("asdf");
StringBuffer* sbptr = &sb; // instance hold by sb
Object* objptr = &sb;
Casting C++ object pointer to ACDK objects:

StringBuffer* sbptr  = new StringBuffer("asdf");
sbptr->addRef(); // make sure, that not be freed
RStringBuffer sb = sbptr;
sbptr->releaseRef(); // releases references

 C++ references


RStringBuffer sb = new StringBuffer("asdf");
StringBuffer& sbref = *sb;
sbref.append("asdf");

 Casting Arrays

Casting Object arrays differs a little bit to casting java Object arrays. Please refer to  Arrays for more information

 < prevConstructs(2 / 12) next >