2010-11-08 108 views
1

發件人:兩個不同的對象

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

接收機:

//不知道如何找到哪個對象,我應該強制轉換的對象:(

有沒有辦法在同一個對象流發送兩個不同的對象?

-PK

+0

socket.writeObject(typeid + B); ??? – 2010-11-08 05:19:09

回答

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

這兩個對象都有關係嗎?一個人繼承了另一個人嗎?如果是這樣,你需要明確檢查。

說(父類) - >乙

B b = new B() 

b instanceof B所以和b instanceof A將爲真。所以你需要小心。首先檢查孩子班。

+0

感謝您的時間。我的東西我dint正確發佈我的問題。我通過一個對象流發送這個對象。我從客戶端通過套接字發送兩個對象。在服務器端,我需要將其轉換爲適當的類型。鋤頭我這樣做嗎? – Blacklabel 2010-11-10 17:14:44

+0

@Blacklabel,我得到了你的問題,我回答正確,使用'instanceof'你可以確定對象屬於哪個類,所以如果'instanceof A'爲true,你可以投擲'(A)對象......它不會拋出異常。 :)試試吧:)我會修改代碼,只是incase。 – st0le 2010-11-11 04:43:23

相關問題