1

I am trying to write a serialization of an object (Match) to a file. However, when I run my code, I receive the following code, stating that the object cannot be serialized because it contains a DateTimeFormatter property which is not serializable:

java.io.NotSerializableException: java.time.format.DateTimeFormatter

The problem is that I can't modify the DateTimeFormatter class to implement java.io.Seralizable, as that interface is marked final.

Any suggestions on how to workaround this issue?

Below is my code:

Match.java

import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Match implements java.io.Serializable {
    private String timeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    private final DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(timeFormat, Locale.ENGLISH);

    public Match() {
    }
}

SaveSerializedMatch.java:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class SaveSerializedMatch{
    public static void main(String[] args) {
        Match match = new Match();
        
        try {
            FileOutputStream fileOut = new FileOutputStream("Match.txt");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
    
            out.writeObject(match);
            out.close();
    
            fileOut.close();
        }
        catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Adam Lee
  • 436
  • 1
  • 14
  • 49
  • Make `inputFormatter` `transient` (and non-`final`), then implement `readObject` in `Match`. Something like `private final void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {in.defaultReadObject(); this.inputFormatter = DateTimeFormatter.ofPattern(timeFormat, Locale.ENGLISH);}` should work. – ernest_k May 17 '21 at 04:33
  • I don't see any reason why both the format and the formatter can't be `static` here. – user207421 May 17 '21 at 05:16

0 Answers0