簡體   English   中英

如何設計一種可以處理兩種不同對象類型的方法

[英]How to design a method that can deal with two different object types

我有兩個集合,它們具有幾乎相似的屬性:

HashSet<BuyerUser>
HashSet<SellerUser>

我想編寫一個將對象序列化為 JSON 並將其發送到 Web API 的方法。 但是,我的問題是,我無法編寫足夠通用的方法,因此我不必重復兩次代碼。

public void addToMetadata (Object users) {

   if (users instanceof BuyerUser) {
        // Do this

    }
    if (users instanceof SellerUser) {
        // Do that

    }
}

我的問題是 instanceOf 檢查不能按照我概述的方式工作。 我將不得不做類似的事情

if (users instanceof HashSet<BuyerUser>)

但這給了我一個錯誤:

llegal generic type for instanceof

可以以任何方式解決嗎?

if (users instanceof HashSet<BuyerUser>)

您不能這樣做,因為在運行 instanceof 調用時,泛型會在運行時被刪除

相反,更好的方法是創建 BuyerUser 和 SellerUser 的父類,或者創建 BuyUser 和 SellerUser 都具有的具有類似功能的接口

public String toJSON ()

由於參數化類型在運行時丟失,因此您不能這樣做。 您可以為每個HashSet創建一個包裝器並為其添加一個返回類型的方法:

public class MySet<T> extends HashSet<T> {
     private Class<T> type;

     public MySet(Class<T> c) {
          this.type = c;
     }

     public Class<T> getType() {
          return type;
     }
}

或者您可以獲取集合的第一個元素並檢查其類型:

if(set instanceof HashSet && !set.isEmpty() && set.iterator().next() instanceof BuyerUser) {
    // BuyerUser set
}

請注意,該set可能包含不同類型的對象,例如將其定義為HashSet<Object>

暫無
暫無

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

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