miss h
miss h

Reputation: 131

(readObject + readresolve ) read as pointer

I want to read an object from file using ObjectInputStream. Here is what the readObject method looks like inside:

public void readObject(ObjectInputStream inbos) throws IOException {
    try {
        GameModel gm =  (GameModel) inbos.readObject();
    } catch (IOException ex) {
        Logger.getLogger(GameDeserializer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(GameDeserializer.class.getName()).log(Level.SEVERE, null, ex);
    }           
}

My GameModel class has a readResolve method. GameModel class is also a singleton.

public Object readResolve() throws ObjectStreamException {
    System.out.println("At read resolve method ");
    GameModel themodel = getGameModel();

    System.out.println("Reading the file : " + themodel.toString() + themodel );
    return themodel;
}

The problem is it is not reading the object right. It is reading it as a pointer. I need help please.

Upvotes: 0

Views: 97

Answers (1)

Daniel Sperry
Daniel Sperry

Reputation: 4491

Your implementation of readResolve() will replace whatever you had written in the stream with the current singleton, so no data from the stream is actually used. (assuming the getGameModel() gets the singleton instance)

Explaining: The ObjectInputStream will instantiate and deserialize a new instance of GameModel, then call readResolve(), which if your current implementation will tell the stream to use the old singleton instead.

If that's what you are trying to do, you should also consider writing an empty writeObject() to avoid writing unnecessary data to the stream.

If that was not what you had in mind and GameModel is really supposed to be a singleton your choices are:

  1. Using readResolve() to copy data from the "just read game model" to the singleton
  2. Using readResolve() to replace the current singleton instance (sounds dangerous)
  3. Any number of tricks with writeReplace/readResolve using a replacement object (like GameModelReplacement) to hold the data you want to save/restore;

About readObject(): It's not clear in your question if that readObject is in GameModel. I'm assuming it's not. However if it is, the statement (GameModel) inbos.readObject(); makes no sense as the GameModel is the current object (this). If that's the case do something like this:

public class GameModel {

    private void readObject(ObjectInputStream inbos) throws IOException {
       // do nothing
    }

    private void writeObject(ObjectOuputStream out) throws IOException {
       // do nothing
    }

    private Object readResolve() throws ObjectStreamException {
        // discarding serialized gamemodel, and using the singleton.
        return getGameModel();
    }
}

Upvotes: 2

Related Questions