Link to home
Start Free TrialLog in
Avatar of matjc
matjc

asked on

Casting objects

Is it possible to find out what type of object an Object is...For example I use an ObjectOutputStream to serialize an Object across a network, however this 'serializer' could be serializing Strings, HashMaps, basically any datastructre. Is there a way when the Object is deserialized at the other end to tell what sort of Object it is? How to I Cast it back to its proper type?
Avatar of bobbit31
bobbit31
Flag of United States of America image

Object o;

if (o.getClass() == String.class) {
  String s = (String) o;
}
Avatar of allahabad
allahabad

String className = object.getClass(); // to get the class name of the object.

Suppose that you got class name "java.util.Vector"
Vector vector = (java.util.Vector) object;
ASKER CERTIFIED SOLUTION
Avatar of fivesigmaevent
fivesigmaevent

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you have choices to check, you can use the methods above. but without choice, I don't think its possible
Avatar of CEHJ
String className = getClass().getName();
Avatar of matjc

ASKER

allahabad,

getClass method actually return an object of type Class so the example given doesnt work however its an insteresting start, unfortunatly you are unable to do the following:

String className = object.getClass().toString;

className myDataStructure = (className)object

using className as the type, this would solve the issue of not necesserily knowing what type of object you are receiving.

any more ideas?
>>getClass method actually return an object of type Class

that's why i posted the correct code ;-)
Avatar of matjc

ASKER

CEHJ,

>>that's why i posted the correct code ;-)

I typed my comment as you submitted yours I guess, anyway any idea how to solve the comment about casting an object to the correct type without knowing in the first instance what type it is?

calling .toName() as apposed to .toString() does not really change the question
>>any idea how to solve the comment about casting an object to the correct type without knowing in the first instance what type it is?

You can't really, but this begs the question of why you would want to do this - i.e. - what are you trying to do?
Avatar of matjc

ASKER

not worth splitting the points, as I have implemented something similar to the accepted answer I have awarded the points to them, it was after all the only code fragment that worked here.
>>it was after all the only code fragment that worked here.

I'm not sure what you mean by that

You could, of course, use the answer you chose

>>to find out what type of object an Object is...<<

as per your question if you are prepared to write an infinite series of

if (o instanceof X)

statements for every possible class in existence now, or at any time in the future. But not otherwise.