I have class that have automatically generated id (instance number) for every object. I need serialized this, then deserialized. Simply done. But the thing is that after deserialization and create new object, this new object should have id higher than highest id from objects before serialization.
For example: I have List of 3 Human(name, automatically generated id):
List<Human> list = new ArrayList<>(); list.add(new Human("Mike", 1)); list.add(new Human("Lisa", 2)); list.add(new Human ("Monica", 3));
Then serialized List list and deserialized in Main2. After that I wanna create next Human and this next Human should have id 4.
How to let know for deserialized List what's the highest id ?
I tried to store max id in static field but I can't access it after serialization (static is default transient)
You'll need to perform some deserialization post-processing by creating a readObject
method. I'd also make the id field transient, as there's no need to serialize it if you're going to replace it.
public class Human implements Serializable {
private static final AtomicLong nextId = new AtomicLong(1);
private transient long id;
private String name;
public Human(String name) {
this.name = name;
this.id = nextId.getAndIncrement();
}
public long id() {
return id;
}
public String name() {
return name;
}
public String toString() {
return id + ": " + name;
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream. defaultReadObject();
id = nextId.getAndIncrement();
}
}
Note how I removed the id
parameter from the constructor; that prevents creating humans with random ids.