In a project, I need to extend the standard class loader with a custom class loader. The main motivation for this is that the classpath is extended during run time. (For a solution to this problem see: https://stackoverflow.com/a/51584718/231397 ).
Serializing objects via
ObjectOutputStream out;
try {
FileOutputStream fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(object);
}
catch(FileNotFoundException e) {}
catch (IOException e) { }
finally {
out.close();
}
works fine, while deserializing objects via
Object object = null;
ObjectInputStream in;
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
object = in.readObject();
}
catch(FileNotFoundException e) {}
catch (ClassNotFoundException e) {}
finally {
in.close();
}
fails with a ClassNotFoundException
exception. The reason is that the standard class loader is invoked, which does not know about the custom class loader.
Q: What is the correct way to deserialize objects using a custom class loader?