3

I have a employee class:

class Employee implements Serializable{
    int empId;
    String empName;
    double salary;
}

One object of this employee class is serialized and stored in some file say employee.ser

I want to add one more field in the existing employee class. Now my employee class will be something like this

class Employee implements Serializable{
    int empId;
    String empName;
    double salary;
    String state="abc";
}

Is it possible to deserialize the old object, such that it will have default value for the state?

If it is possible, then how?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • I am not entirely sure but it can be done based on serial version id. So for the first employee id lets say the serial version id was 1, and for the updated class the serial version id is 2. A de-serializer can be implemented to check the serial version id and update the fields based on it. – Jaiprakash Jun 22 '16 at 11:19
  • @Jaiprakash No it can't. If you change the `serialVersionUID` there will be an exception long before any of your code is run. That's why you shouldn't change it, – user207421 Jun 22 '16 at 12:03
  • Yes, it can be done using custom deserializer. Steps are: 1. Donot change serialVersionUID. Step 2: Implement custom deserializer. Sample code: class CustomDesrializer extends ObjectInputStream{ public CustomDesrializer(FileInputStream fileIn) throws IOException{super(fileIn);} public Employee customReadObject() throws ClassNotFoundException, IOException{ Employee obj = (Employee )super.readObject(); if(obj.state == null) obj.state= "abc"; return obj; } } – Swaraj Shekhar Jun 22 '16 at 12:06
  • thanks Swaraj. it worked :) – Abhishek Kumar Maurya Jun 22 '16 at 17:38

2 Answers2

2

Yes. You can add or delete fields. See the Object Versioning chapter of the Object Serialization Specification. Make sure to keep the serialVersionUID the same value. However applying a default value is up to you, as no constructor or initialization code is run on deserialization.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

I see this is an old question, but maybe can help others...

In your class you can implement method 'readObject'.

This method is called on deserialize the object.

e.g.:

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    if (newField == null) {
        newField = "abc";
    }
}
Batsheva
  • 659
  • 4
  • 13
  • 27