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

发布于 2024-09-30 17:22:18 字数 232 浏览 4 评论 0原文

发送者:

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

接收者:

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

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

-Pk

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千鲤 2024-10-07 17:22:18

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

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

说A(父类)-> B

B b =  new B()

,因此 b instanceof Bb instanceof A 将为 true。所以你需要小心。首先检查子类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文