Blacklabel
Blacklabel

Reputation: 846

Two different objects on the same socket in Java

Sender:

ObjectA A = new ObjectA();
ObjectB B = new ObjectB();
//Connection is created
socket.writeObject(B);

Receiver:

//don't know how to find to which object I should typecast the object to :(

Is there any way to send two different objects on the same Object stream?

-Pk

Upvotes: 1

Views: 1067

Answers (1)

st0le
st0le

Reputation: 33545

use instanceof

A a = new A();
B b = new B();
C c = new C();
 //say obj is the object you read from your socket.
if(a instanceof A){
      System.out.println("a is instance of A, obj can be cast as A");
      A remoteA = (A)obj; //wont throw classcast exception!!
}
if(b instanceof B){
      System.out.println("b is instance of B, obj can be cast as B");
      B remoteB = (B)obj; //wont throw classcast exception!!
}
if(c instanceof C){
      System.out.println("c is instance of C,obj can be cast as C"); 
      C remoteC = (C)obj;  //wont throw classcast exception!!
}

Are both the objects related? does one inherit the other? If so you'll need to check explicitly.

Say A (parent class) -> B

B b =  new B()

so b instanceof B and b instanceof A will be true. So you need to be carefull. Check the child class first.

Upvotes: 4

Related Questions