I'm trying to write a general method that writes different types of Java Beans (so List<JavaBean>
) to a file. I'm currently constructing a FileManager
utility class. Each Java Bean implements the same interface. Here's an example of what I'm trying to do.
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 }
}
I want to be able to pass a List<RecipeData>
and a List<DemographicData>
to this method. Obviously what I have does not work.
It doesn't seem I can even do the following:
List<Data> data = new ArrayList<RecipeData>();
How would this normally be done? In Swift I might use the as? keyword to cast it to the correct type.
**************EDIT**************
Just to preface I'm using the SuperCSV library to assist in parsing rows into a Java Bean and I am using the accepted answer below for the method definition. So I have the following code:
Data dataset;
while((dataset = beanReader.read(Data.class, nameMappings, processors)) != null ) {
container.add(dataset);
}
I get the following error:
The method add(capture#1-of ? extends Data) in the type List is not applicable for the arguments (Data)
dataset needs to be either type RecipeData or DemographicData for this to work I'd assume. Is there an easy way to fix this so that it is flexible if I add more Beans in the future?