[英]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 -PK
use instanceof
使用
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 说A(父类) - > B.
B b = new B()
so b instanceof B
and b instanceof A
will be true. 所以
b instanceof B
和b instanceof A
将是真的。 So you need to be carefull. 所以你需要小心。 Check the child class first.
首先检查子课程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.