简体   繁体   English

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

[英]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 Bb instanceof A将是真的。 So you need to be carefull. 所以你需要小心。 Check the child class first. 首先检查子课程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中的不同类中使用相同类型的两个不同对象 - Using two different objects of the same type in different classes in Java 不同哈希码的结果,但对于两个java对象而言,结果相同 - Consequences of different hashcodes but same equals for two java objects 如何在Java中为两个不同的对象调用相同的方法 - How to call the same method for two different objects in Java java - 以不同的顺序比较两个具有相同键的json对象 - java - Compare two json objects with same keys in different order Java:将两个具有相同值的不同类型的对象进行比较,返回true - Java: comparing two Objects of different type with same value, returning true 在同一TCP套接字上接收不同类型的对象 - Recive different type of objects on the same TCP socket Java - 映射包含对象列表的两个对象(具有不同命名但功能相同的对象) - Java - Map two objects containing List of objects(objects which have different naming but same function) 具有相同数据Java的不同对象 - Different objects with the same data java Java-同一TCP IP的不同套接字 - Java - Different socket for same TCP IP 在比较Java中的两个基元和两个对象时,==实际上是相同还是不同? - Does == actually work the same or different when comparing two primitives vs two Objects in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM