2016-06-13 143 views
1

我正在嘗試編寫一種將不同類型的Java Bean(所以List<JavaBean>)寫入文件的常規方法。我目前正在構建一個FileManager實用程序類。每個Java Bean都實現相同的接口。這是我想要做的一個例子。Java:將實現相同接口的不同自定義對象傳遞給方法

public interface Data { method declarations } 
public class RecipeData implements Data { class stuff goes here } 
public class DemographicData implements Data { class stuff goes here } 

final public class FileManager { 
    public static void writeToCsvFile(String filename, List<Data> data) { file writing logic goes here } 
} 

我希望能夠通過一個List<RecipeData>List<DemographicData>這個方法。很明顯,我有什麼不工作。

它似乎沒有我甚至可以做到以下幾點:

List<Data> data = new ArrayList<RecipeData>(); 

這將如何,通常做什麼?在Swift中,我可能會使用as?關鍵字將其轉換爲正確的類型。

**************編輯**************

只是爲了前言我使用的SuperCSV庫,以協助將行解析到Java Bean中,我使用下面接受的方法定義的答案。所以,我有以下代碼:

Data dataset; 
while((dataset = beanReader.read(Data.class, nameMappings, processors)) != null) { 
    container.add(dataset); 
} 

我得到以下錯誤:

The method add(capture#1-of ? extends Data) in the type List is not applicable for the arguments (Data)

數據集必須是兩種類型RecipeData或DemographicData這個工作我會承擔。有沒有一種簡單的方法來解決這個問題,以便在將來添加更多豆類時它是靈活的?

+0

您收到的錯誤是什麼? –

+0

'List <?實現數據>數據=新ArrayList ();' –

+0

更新後的底部,我收到錯誤。我正在使用接受的答案方法聲明。 –

回答

2
final public class FileManager { 
    public static void writeToCsvFile(String filename, List<? extends Data> data) { file writing logic goes here } 
} 

另外,你可以聲明

List<Data> data = new ArrayList<RecipeData>(); 

List<Data> data = new ArrayList<Data>(); 

,或者在Java 7中,

List<Data> data = new ArrayList<>(); 

,只是用RecipeData填充它,因爲無論哪種方式你正在失去信息在此List將僅包含RecipeData

+0

當我以這種方式聲明我的方法時,這給了我一個編譯器錯誤「數據無法解析爲類型」。 –

+0

好..是在FileManager類中導入的數據? –

+0

它在同一個包中,所以我不認爲這很重要。如果你說的是真的,我可以不這樣做: public static void writeToCsvFile(String filename,List data) –

相關問題