Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

java - 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.

question from:https://stackoverflow.com/questions/65871013/can-i-clone-an-object-if-i-have-access-only-to-its-interface-and-is-not-serializ

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...