Java中同一个套接字上的两个不同对象

时间:2010-11-08 05:09:56

标签: java sockets networking

发信人:

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

接收器:

//不知道如何找到我应该将对象强制转换为哪个对象:(

有没有办法在同一个Object流上发送两个不同的对象?

-PK

1 个答案:

答案 0 :(得分:4)

使用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!!
}

这两个对象是否相关?一个人继承了另一个吗?如果是这样,您需要明确检查。

说A(父类) - >乙

B b =  new B()

所以b instanceof Bb instanceof A将成立。所以你需要小心。首先检查子课程。