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());
}
}
}