Here is the class stealing reference to a copy of a singleton while singleton is deserialized.
public class ElvisStealer implements Serializable {
static Elvis impersonator;
private Elvis payload;
private Object readResolve() {
// Save a reference to the "unresolved" Elvis instance
impersonator = payload;
// Return an object of correct type for favorites field
return new String[] { "A Fool Such as I" };
}
private static final long serialVersionUID = 0;
}
My questions are:
- Where and how exactly is a copy of Elvis object reference aquired? This part does not say much about that.
// Save a reference to the "unresolved" Elvis instance impersonator = payload;
In other words, how can child object's readResolve
access parent object reference?
To make ElvisStealer work I have to modify serialized data by replacing singleton instance field of type
String[]
(in that case) with ElvisStealer instance. In the book singleton contains a nontransient
String[]
instance field and that field is replaced with ElvisStealer instance in serialized stream. Then when that field is deserialized,ObjectInputStream
sees that this field is of type ElvisStealer and it invokesreadResolve
from ElvisStealer class. My questions are: why JVM don't give an error parsing such field knowing that there should be String instead of ElvisStealer and secondly why JVM invokesreadResolve
from ElvisStealer class knowing that there should beString[]
, not ElvisStealer.Why ElvisStealer contains an instance field of type Elvis in addition to static field? Shouldn't be static field enough?