简体   繁体   中英

Can I clone an object if I have access only to its interface and is not serializable?

I have the interface of an object. I don't know if the implementation is serializable or not. Nor Cloneable. And I don't have getters of object properties, actually, I don't know the properties either.

Can I still clone the object? I mean, can I do something like:

public void copyMyObject(MyObject myObject){
    this.copyOfMyObject = ...//? can I make a deep copy?

}

I guess not...but maybe I am missing something.

Well... it depends.

You can serialize an object if the object's actual class implements Serializable ... and the rest 1 . 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 coding 2 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM