发件人:

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

接收者:

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

有什么方法可以在同一对象流上发送两个不同的对象吗?

-PK

最佳答案

使用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 b =  new B()

因此b instanceof Bb instanceof A将为true。因此,您需要谨慎。首先检查 child 类(class)。

关于java - Java中同一套接字上的两个不同的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4121436/

10-11 03:54
查看更多