I have this code do load any serialized data:
public static <T> T loadData(String filename) {
T o = null;
try {
FileInputStream fi = new FileInputStream(filename);
ObjectInputStream oi = new ObjectInputStream(fi);
o = (T) oi.readObject();
oi.close();
fi.close();
} catch (Exception e) {}
return o;
}
I call it with this:
ArrayList<String> data = loadData("a.dat");
But in this file I have another serialized object (e.g. a java.util.File
object).
I expected a error at o = (T) oi.readObject();
, which would be catched, but it crashes in the method call.
Why?
EDIT: Okay problem solved with the following code:
public static <T> T loadData(Class<T> expectedClass, String filename) {
T o = null;
try {
FileInputStream fi = new FileInputStream(filename);
ObjectInputStream oi = new ObjectInputStream(fi);
o = expectedClass.cast(oi.readObject());
oi.close();
fi.close();
} catch (Exception e) {}
return o;
}