I have files containing object logs. Each file can store objects of a different type, but one file is homogeneous - it stores only objects of one type.
I would like to write a method that returns an array of these objects, and have an array of the specified type (the type of objects in the file is known and can be passed as a parameter).
Roughly speaking, I want 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 does not compile (there is an error in the return statement and a warning when creating), but it should give you an idea of what I'm trying to do. Any suggestions on the best way to do this?
source
share