Well ... it depends.
You can serialize an object if the object's actual class implements Serializable
... and the rest1. The actual type may be different to the (static) type of the variable where you are getting the object's reference from.
But if not, then you are not missing something. Deep copying an object that doesn't implement its own deep copy methods, getters and setters, or some form of serialization, would involve some extremely nasty coding2.
You are better off designing your classes so that they can be serialized / cloned. Or, so that you don't need to clone them.
Note that there are a few Java classes that would be impossible to clone correctly even by "nasty" means. Examples include Thread
, Socket
, Class
, ClassLoader
and some key awt
classes. So if your (hypothetical) application design depended on (say) being able to clone a running thread, that design would not be implementable.
1 - Instance fields that are not transient
and not null
need to be serializable as well. And so on.
2 - For example, you could conceivably make use of abstraction breaking reflection and use of the Unsafe
to replicate what the object serialization implementation does under the hood ... without the Serializable
type check. It is a bad idea though.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…