Shelef
Shelef

Reputation: 668

How can I know the object type sent by a socket?

I am using Java. I make connection using sockets and I send from the server objects using ObjectOutputStream. There is two types of object that can be sent, one type is object which is instance of class A and the other type which is instance of class B. When I read Object in the client side, how can I decide if it is instance of class A or instance of class B?

PS: I have accsess to these classes in the client side too.

Upvotes: 3

Views: 1684

Answers (4)

Synesso
Synesso

Reputation: 38978

Alternatively, use a plaintext form of serialisation & embed the name of the type (or perhaps deserialisation strategy) in the serialised payload. This way you can inspect the payload before deserialising.

Upvotes: 0

Philipp
Philipp

Reputation: 69663

Either use

if (object instanceof ClassA) {

or

if (object.getClass() == ClassA.class) {

The difference is that the first will also be true when object is of a sub-class of ClassA or implements ClassA (when it's an interface), while the second one will only be true when it's exactly that class.

Upvotes: 2

Srikant Krishna
Srikant Krishna

Reputation: 881

Yes, the instanceof operator is the best method.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

The simples solution is to use instanceof operator on input:

final Object obj = inputStream.readObject();
if(obj instanceof A) {
  final A a = (A)obj;
} else {
  final B a = (B)obj;
}

Slightly redundant solution (but avoiding instanceof) would be to send some type byte first (0 - A, 1 - B).

Upvotes: 3

Related Questions