Search code examples
javafileobjectserializable

Is there a way to make current class point to the new object that has just been read in Java Serializable?


I am trying to read an object for a SocialNetwork Simulation. The read methods makes use of Java Serializable. The code looks like this:

public class SocialNetwork  implements Serializable{

// lots of fields

public SocialNetwork(){
//lots of inilization
} 
    public void writethisObject() throws IOException{
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("Simulation.bin"));
            objectOutputStream.writeObject(this);
        }

        public void readfromObject(File f) throws IOException, ClassNotFoundException{
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
            SocialNetwork newSocialNetwork = (SocialNetwork) objectInputStream.readObject();
            this = newSocialNetwork;
        }

}

However as you can see I am trying to make the current class point to the object that I just read by making this = newSocialNetwork. This gives me an error as expected. I can work around this by making each and every field of the current SocialNetwork class to the newSocialNetwork. However, I do not want to do that as there are tons of field in my class. And it would look very messy. I hope you have got the idea of what I am trying to do.


Solution

  • Since you cannot override this in Java and you want to have only one instance of your class use a Singelton Pattern:

    public class SocialNetwork  implements Serializable{
        // lots of fields
    
        private static SocialNetwork myself = new SocialNetwork();
    
        private SocialNetwork(){ // private constructor
            //lots of inilization
        }
    
        public static SocialNetwork getInstance() { 
            return myself; 
        }
    
        public void writethisObject() throws IOException{...}
    
        public void readfromObject(File f) throws IOException, ClassNotFoundException{
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
            myself = (SocialNetwork) objectInputStream.readObject();
        }
    
    }