簡體   English   中英

如何投放清單 <T> 能夠在各個對象上調用特定方法?

[英]How to cast List<T> to be able to call specific method on respective Object?

我對List的泛型轉換有一些想法,但老實說,我不知道是否有可能實現。

我的應用程序中有此代碼段

public String getObjectACombo() {
   List<ObjectA> listA = theDAO.getObjectA();
   String combo = getCombo(listA, "rootA"); // --> This line
}

public String getObjectBCombo() {
   List<ObjectB> listB = theDAO.getObjectB();
   String combo = getCombo(listA, "rootA"); // --> This line
}

首先,我為提到的“->此行”行編寫了一些例程。 但是,這兩種方法具有完全相同的算法,可以從數據庫返回的List <?>生成JSON字符串。 因此,我正在考慮用通用方法getCombo(List <T> list,String root)替換它們。 但問題是我無法使它起作用。

public <T> String getCombo(List<T> list, String root) {
   Iterator<T> listItr = list.iterator();

   ...
   while ( listItr.hasNext() ) {
      jsonObj.put(list.get(i).toJson());  // --> The Error line
   }
}

錯誤發生在“錯誤行”上。 ObjectA.java和ObjectB.java都具有toJson()方法,但是在上述行中“類型T未定義toJson()方法”。

我嘗試使用(T)和Class.forName()進行轉換,但它們都沒有起作用。

有沒有解決這個問題的辦法? 可能嗎

使用定義toJson()方法的接口,例如Jsonable :)-然后限制T

public <T extends Jsonable> String getCombo(List<T> list, String root) { 
 ...
}

這樣,編譯器知道每個T必須從Jsonable繼承,並因此具有toJson()方法。

編輯:這是我的意思的示例,使用已經存在的Comparable<T>接口:

public <T extends Comparable<T>> boolean compare(List<T> list, T other) {
  for( T object : list ) {
    if( object.compareTo( other ) == 0 ) {
      return true;
    }
  }    
  return false;
}

compare( new ArrayList<String>(), "foo"); //compiles, since String implements Comparable<String>
compare( new ArrayList<Object>(), null); //doesn't compile, since Object doesn't implement Comparable<Object>

嘗試對每個使用a:

public <T> String getCombo( List<T> list, String root )
{
    for (T x : list)
    {
        //do stuff here
    }
}

暫無
暫無

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

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