我想通过调用这个方法来获得一个序列化的对象:
ArrayList<String> myArrayList = (ArrayList<String>) getSerializedObject(ArrayList.class, "arraylist.ser");
如果指定的文件(arraylist.ser)不存在,或者与我传入的类不匹配,我想返回该类的一个新实例。
private Object getSerializedObject(Class<?> c, String filename) {
Object serObject = null;
try {
if (new File(filename).exists()) {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
Object tempObj = in.readObject();
if (tempObj.getClass().equals(c)) {
System.out.println("Loading "+filename);
serObject = tempObj;
}
in.close();
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
if (serObject != null) {
return serObject;
}
else {
// return new instance of Class c here
}
}