I understand that serialization is a quick way to save instances of objects, including all variables within the objects, excluding static references and those marked with the transient keyword.
I’m not very good with I/O and my application has about 50 classes of which there are three distinct different objects (which contain objects within them).
For example, I have an Animal Class, Employee Class, Vehicle Class. All which contain instance objects, at run time, which contain their own subclasses, methods, etc.
My question is, what is the easiest way to save all this information with Serialization? I have discussed this problem with my professor and he suggested something like an encompassing class “Data.class” that has it’s “hands” in everything, and then Serializing that. Which would end up saving every object it references to the .ser file.
I thought about making the “Data.class” and then making all my 50 classes, extend Data.
and then having my save method do something like
public void saveData(){
Data myData = new Data()
try
{
FileOutputStream fileOut =
new FileOutputStream("Data.ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(myData);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
However, I can’t seem to get this to work. I believe it is because I am creating a blank instance of Data which contains only default values for all the subclasses. I am calling the function when I do intend to save (after all values in their corresponding objects are filled), but I am doing something wrong and can’t figure out what.
Any help would be greatly appreciated. Surely I don’t have to manually serialize every single instance of the three different types of objects? It is over 300 and I’d prefer not to do that.
Also, I did give Data a serialVersionID and implement the serializable interface for Data.
Make sure all your classes implements the
Serializableinterface and thisDataclass has the methods to serialize/deserialize yourAnimal,Employee,Vehicleand other classes.You can do this easily by having a single method
saveData(Serializable serializable, String fileName). This would be a skeleton for your needs (based in your actual code):