I’m creating an undo-redo mechanism. To achieve this, I’m using Serialization. Recording the current state by writing it to a ByteArrayOutputStream, using ObjectOutputStream and putting the byte[] into an ArrayList.
But the problem is that, some of the classes are holding a reference/pointer to a BufferedImage. Which I don’t want to serialize because of its size (and it doesn’t implement Serializable). The reason why I don’t want to write it is that it will never change. But it is a different image for each instance of the class, so the static keyword isn’t a solution.
My attempt to solve:
public transient BufferedImage img;
This causes the ObjectOutputStream will not serialize the BufferedImage, but it won’t store the reference as well. After deserializing, it will be null.
So, in short, I want to keep the reference to the object, but not the object itself. Which means that, after deserialazing I will be able to use the BufferedImage (because of it isn’t removed by the Garbage Collector).
Many thanks.
OK, simple enough, keep a
Map<String, BufferedImage>of all images somewhere in your application, let each of your classes serialize the key to its image. And in thereadResolve()method, look up the image from the map.