I have some files that contain logs of objects. Each file can store objects of a different type, but a single file is homogeneous — it only stores objects of a single type.
I would like to write a method that returns an array of these objects, and have the array be of a specified type (the type of objects in a file is known and can be passed as a parameter).
Roughly, what I want is something like the following:
public static <T> T[] parseLog(File log, Class<T> cls) throws Exception {
ArrayList<T> objList = new ArrayList<T>();
FileInputStream fis = new FileInputStream(log);
ObjectInputStream in = new ObjectInputStream(fis);
try {
Object obj;
while (!((obj = in.readObject()) instanceof EOFObject)) {
T tobj = (T) obj;
objList.add(tobj);
}
} finally {
in.close();
}
return objList.toArray(new T[0]);
}
The above code doesn’t compile (there’s an error on the return statement, and a warning on the cast), but it should give you the idea of what I’m trying to do. Any suggestions for the best way to do this?
You can’t have generic arrays, so just return the ArrayList from your method:
Then, when you know the actual type, do the cast then. So assuming you know that T is actually an Integer at some point, do this: