gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:00:08 24 4
gpt4 key购买 nike

发件人:

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 将为真。所以你需要小心。先检查子类。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com