Casting an object at runtime
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Eelco_Cramer
Posted On:   Friday, September 7, 2001 06:52 AM

I have a small problem, when an object is returned from a hashtable I don't now the objectype @ compiletime. What I could do is something like: HashTable hash = ... ... Object theObject = Hashtable.get("theKey"); if (theObject.getClass().getName().compareTo("Ljava.lang.String")) { theString = (String)theObject; } else if ( ... ... } else { System.out.println("BOOO, I didn't program the correct object type!"); } Does anyone know a more generic solution? I like to cast the object at runtime! Cheers, Eelco    More>>

I have a small problem, when an object is returned from a hashtable I don't now the objectype @ compiletime. What I could do is something like:


			
HashTable hash = ...
...

Object theObject = Hashtable.get("theKey");

if (theObject.getClass().getName().compareTo("Ljava.lang.String")) {
theString = (String)theObject;
}
else if ( ...
...
}
else {
System.out.println("BOOO, I didn't program the correct object type!");
}


Does anyone know a more generic solution? I like to cast the object at runtime!


Cheers,


Eelco

   <<Less

Re: Casting an object at runtime

Posted By:   John_Zukowski  
Posted On:   Friday, September 7, 2001 07:40 AM

It is called instanceof.


if (theObject instanceof String)


String being the classname (java.lang.String)

About | Sitemap | Contact