简体   繁体   English

如果我只能访问 object 的接口并且不可序列化,我可以克隆它吗?

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

I have the interface of an object.我有一个 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.而且我没有 object 属性的吸气剂,实际上,我也不知道这些属性。

Can I still clone the object?我还能克隆 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 .如果对象的实际 class 实现Serializable ... 和 rest 1 ,则可以序列化 object 。 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 .深复制没有实现自己的深复制方法、getter 和 setter 或某种形式的序列化的 object 将涉及一些非常讨厌的编码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.请注意,有一些 Java 类即使通过“讨厌”的方式也无法正确克隆。 Examples include Thread , Socket , Class , ClassLoader and some key awt classes.示例包括ThreadSocketClassClassLoader和一些关键的awt类。 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. 1 - 非transient且非null的实例字段也需要可序列化。 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. 2 - 例如,您可以想象利用破坏抽象的反射和使用Unsafe来复制 object 序列化实现在幕后所做的......没有Serializable类型检查。 It is a bad idea though.不过这是个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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