2012-10-30 242 views
1

我很難用google搜索這個。我發現了很多文章,但我仍然無法解決我的問題。java - 鑄造泛型

這裏是我的代碼:

List<MyMainClass> mySource = (List<MyMainClass>) session.getAttribute("myAttribute");

session.getAttribute( 「myAttribute」)可能返回List<MyObject1>List<MyObject2>。無論MyObject1MyObject2MyMainClass子現在我有2種功能。第一個接受List<MyObject1>,另一個接受List<MyObject2>。現在即時得到月食

The method myMethod1(List<MyObject1>) in the type MyAction is not applicable for the arguments (List<MyMainClass>)

+0

你可以添加其中'myMethod1'定義代碼,以及如何正在調用它?看起來'myMethod1'需要一個'MyObject1'列表,但是你傳遞一個MyMainClass'列表,這個列表不會被接受。 –

回答

1

你不能安全地存儲不同泛型類型,在一個會話屬性相同的擦除(List)錯誤。所以:不要這樣做。

而是重構您的代碼,以便它兼容,而不管該會話屬性的列表類型如何。這可能很難,但長期來看似乎不太臭。 IME,當你需要在一個變量中存儲兩種可能不同類型的東西時,它通常是一種糟糕的設計。

您可以交替使用兩個不同的會話屬性,以便知道要投射到哪個更具體的列表類型。

List<MyObject1> mySource1 = (List<MyObject1>) session.getAttribute("myAttribute1"); 
if (mySource1 == null) { 
    List<MyObject2> mySource2 = (List<MyObject2>) session.getAttribute("myAttribute2"); 
    if (mySource2 == null) { 
     // ??? 
    } else { 
     // rock and roll 
     myMethod2(mySource2); 
    } 
} else { 
    // proceed 
    myMethod1(mySource1); 
} 

如果你採取後一種方法,我建議編寫一個包裝對象或方法來爲你管理這些細節。

0

這是正確的。泛型只提供編譯時間保護。您正嘗試將更通用的列表類型傳遞給更具體類型的list類型的函數。

瞭解List<MyMainClass>的實例可以同時擁有MyObject1MyObject2的實例。當您撥打function1(List<MyObject1>)時,此功能預期列表中的所有元素的類型爲MyObject1。因此,您無法傳遞類型爲List<MyMainClass>的列表。

您需要有可識別的變量來存儲不同類型的列表。

0

建議,這有點棘手。如果你真的想這樣做,我認爲你可以如下做到這一點:

List<MyMainClass> mySource = 
          (List<MyMainClass>) session.getAttribute("myAttribute"); 
if(mySource != null && !mySource.isEmpty()){ 
     //Get the first element and check the type 
     MyMainClass firstElement = mySource.get(0); 
     if(firstElement instanceof MyObject1){ 
      List<MyObject1> mySourceObj1 = (List<MyObject1>)mySource; 
      myMethod1(mySourceObj1); 
     }else{ 
      List<MyObject3> mySourceObj2 = (List<MyObject2>)mySource; 
      myMethod1(mySourceObj2); 
     } 
    } 
0

我會建議你改變你聲明MYSOURCE的方式,如果可能的你的函數簽名。

聲明是這樣的:

List<? extends MyMainClass> mySource = (List<MyMainClass>) 

session.getAttribute("myAttribute"); 

而且從

returnType fun(List<Object1> object1List){ 
} 

改變你的函數簽名

returnType fun(List<? extends MyMainClass> object1List){ 
}