Pass the return type as a parameter in java?
- by jonderry
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?