簡體   English   中英

Java確保傳遞給方法的對象擴展給定的類

[英]Java insuring that an object passed to a method extends a given class

檢入傳遞給給定類擴展方法的對象的最佳方法是什么?

目前,我有一種方法,該方法需要發送一個ByteBuffer數據並編寫一個“ player”類,並將數據排隊在IO服務器上以發送給客戶端:

public void send(ButeBuffer toSend, Player player)
{
  // prep the byte buffer for sending, and queue it on the IO server
}

我想做的就是讓傳入的玩家對象成為擴展玩家類的任何對象。 我進行了一些搜索,發現了以下內容:

public void send(ByteBuffer toSend, Player<? extends Player> player)
{   
   // prep the byte buffer for sending, and queue it on the IO server
}

但這給了我編譯錯誤,而且我不完全了解發生了什么。 這是執行此操作的正確方法嗎? 如果是這樣,誰能解釋該代碼在做什么,為什么它不起作用,或者將我鏈接到一篇對此有更詳細說明的文章。

另外,我想我可以像這樣設置它:

public void send(ByteBuffer toSend, Object player)
{
  // Check that the player extends Player, using instanceof or something 
  // along those lines   

  // Prep the ByteBuffer, and queue the data to send
}

但是,與上述代碼相比,該代碼對我來說有點脆弱。

任何幫助都是最歡迎的。 謝謝 :)

如果我沒記錯的話,您可以保留第一個語法(期望使用Player對象),並且它可以與Player的任何子類一起使用。 那是多態性。

您當前的send定義已經接受Player任何子類(或實現,如果您以后決定將Player用作接口)。

當前,您的方法將接受Player的任何子類(如果您使用第一種方法)。 但是,如果您想通過接口執行此操作(以確保實現了特定方法並可以調用它們),則可以嘗試對類進行泛化並執行以下操作:

public class MyClass<T extends PlayerInterface> {
   public void send(ByteBuffer toSend, T player) {    
      // prep the byte buffer for sending, and queue it on the IO server
   }  
}

但這可能太過分了。 在這種情況下,最好只使用接口作為參數:

public void send(ByteBuffer toSend, PlayerInterface player) {    
   // prep the byte buffer for sending, and queue it on the IO server
}  

您的第一種方法很好。

public void send(ButeBuffer toSend, Player player)
{
  // prep the byte buffer for sending, and queue it on the IO server
}

它確保只有Player類型的對象(或擴展Player的對象)才是有效參數。

我建議使用接口定義允許的參數和不允許的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM