F
Frank Fredstone
I have code that I want to execute only once ever, as a side-effect of
constructing an object. I have put this in a static initializer. But,
if I want to allow the object to be serialized I seem to be stuck,
since the initializer is executed during deserialization.
In the java developer's almanac:
http://www.exampledepot.com/egs/java.io/DeserSingle.html
There's an example of a serializable singleton:
public class MySingleton implements Serializable {
static MySingleton singleton = new MySingleton();
private MySingleton() {
}
// This method is called immediately after an object of this
// class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return singleton;
}
}
If I add code to the constructor, it executes during
deserialization, so that doesn't work for me.
Is there someway to determine within a static initializer or
constructor that this object is being constructed and not being
deserialized? If there were I could execute code only during the one
construction of the object, and not again.
I was thinking that I could implement readObject/writeObject. But, how can
I implement writeObject? How do you represent the fields?
In the oreilly RMI book there is an example of a writeObject method,
but it doesn't explain how you are supposed to represent fields of the
object. I've looked around a bit and found nothing.
constructing an object. I have put this in a static initializer. But,
if I want to allow the object to be serialized I seem to be stuck,
since the initializer is executed during deserialization.
In the java developer's almanac:
http://www.exampledepot.com/egs/java.io/DeserSingle.html
There's an example of a serializable singleton:
public class MySingleton implements Serializable {
static MySingleton singleton = new MySingleton();
private MySingleton() {
}
// This method is called immediately after an object of this
// class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return singleton;
}
}
If I add code to the constructor, it executes during
deserialization, so that doesn't work for me.
Is there someway to determine within a static initializer or
constructor that this object is being constructed and not being
deserialized? If there were I could execute code only during the one
construction of the object, and not again.
I was thinking that I could implement readObject/writeObject. But, how can
I implement writeObject? How do you represent the fields?
In the oreilly RMI book there is an example of a writeObject method,
but it doesn't explain how you are supposed to represent fields of the
object. I've looked around a bit and found nothing.