23
public class MyObj implements Serializable {
  private transient Map<String, Object> myHash = new HashMap<String, Object>();
  ...
}

Is there any way to ensure that when an object of the above class is deserialized the member myHash will be set to a new empty Map rather than be set to null?

ʞɔıu
  • 47,148
  • 35
  • 106
  • 149
  • is it not setting the default values already? is this a singleton class? – fmucar Jan 27 '11 at 00:07
  • 5
    @fatih Deserialization doesn't call your constructors or your field initializers. It's an important lesson, it can save you hours of hassle debugging seemingly good code that suddenly ceases to work. – biziclop Jan 27 '11 at 00:19
  • 2
    it wont call any functions or constructors but apperantly it is not executing class scope inited object inits as well. learning new things everyday. thx. – fmucar Jan 27 '11 at 09:38

3 Answers3

34
public class MyObj implements Serializable {
    private transient Map<String, Object> myHash = new HashMap<String, Object>();

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();

        myHash = new HashMap<String, Object>();
    }
}
timon
  • 473
  • 5
  • 4
  • 4
    A little explanation to go with the code would improve your answer. Code-only answers only make sense to those who already know what they're doing! – Robino Oct 31 '17 at 16:45
11

What about adding a readObject method like this:

public class MyObj implements Serializable {
  private transient Map<String, Object> myHash = new HashMap<String, Object>();
  ...
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();     
    myHash = new HashMap<String, Object>();
  }
}

That should sort you out.

Kristof Neirynck
  • 3,934
  • 1
  • 33
  • 47
Dalibor Novak
  • 575
  • 5
  • 17
3

You can implement your own custom readIn method and explicitly create a new Map<T> as explained in the Java Serializable documentation. That article should describe how to do what you're looking for; check the section entitled Customize the Default Protocol.

Thorn G
  • 12,620
  • 2
  • 44
  • 56