What is the best way to use Serialization in Java?


December 2018


414 time


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()
         FileOutputStream fileOut =
         new FileOutputStream("Data.ser");
         ObjectOutputStream out =
                            new ObjectOutputStream(fileOut);
      }catch(IOException i)

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.

2 answers


Убедитесь , что все классы реализуют Serializableинтерфейс и этот Dataкласс имеет методы для сериализации / десериализации ваших Animal, Employee, Vehicleи других классов.

Вы можете сделать это легко, имея один метод saveData(Serializable serializable, String fileName). Это было бы скелет для ваших нужд ( на основе в Вашем коде):

public class Data {

    public void saveData(Serializable serializable, String fileName) {
        try {
            FileOutputStream fileOut = new FileOutputStream(fileName);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
        } catch(IOException i) {

Отметить все , переменные , которые вы не хотите сериализовать кратковременную или статичный. Посмотрите здесь , если вам нужна дополнительная информация или любопытны.