发信人:
ObjectA A = new ObjectA();
ObjectB B = new ObjectB();
//Connection is created
socket.writeObject(B);
接收器:
//不知道如何找到我应该将对象强制转换为哪个对象:(
有没有办法在同一个Object流上发送两个不同的对象?
-PK
答案 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 B
和b instanceof A
将成立。所以你需要小心。首先检查子课程。