1

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.

1
  • fwiw instanceof exists, no need to do getClass().equals() Commented Aug 9, 2012 at 20:47

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

0

You can use instaceof I believe to check the type.

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

1 Comment

Also, I think using getClass().equals() runs into problems with subclass/superclass and the like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.