Jake B
Jake B

Reputation: 682

Multiple types of objects through an ObjectInputStream in Java

I am trying to use ObjectStreams to send and receive data through a socket connection. I would be using the RMI interface however android doesn't support it. Through my implementation I have multiple kinds of objects that I would like to read through the stream. For example if the client wanted to disconnect from a specified room they would send a Disconnect object through, if they wanted to chat someone they would send a chat object through ect.

I know that you have to type cast to use the object in java as so:

joinRoom = (Room) clientInput.readObject();

but if is there a way if i declare a generic object to tell what type it is and then determine how i will handle it?

maybe like this:

Object obj;
obj = (Object) clientInput.readObject();

and then use?

if(obj.getClass().equals(Room)){....}
if(obj.getClass().equals(Disconnect)){....}

thanks in advance.

Upvotes: 1

Views: 1809

Answers (2)

Heisenbug
Heisenbug

Reputation: 39164

Use instanceof instead:

if(obj instanceof Room)
{
    Room room = (Room) obj;
}

instanceof uses RTTI (Run Time Type information) to check that the base class reference (obj) correspond effectively to a given type at runtime (Room). Then you can perform the cast safely (you won't never encounter a ClassCastException).

Upvotes: 3

Brandon Ling
Brandon Ling

Reputation: 3909

You can use instaceof I believe to check the type.

.equals() is better for checking strings to see if they are the same

Upvotes: 0

Related Questions