zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java cloneable_java浅克隆和深克隆

JAVA 克隆 cloneable
2023-06-13 09:14:59 时间

先来看看JDK的解释:

java.lang.Cloneable

A class implements the Cloneable interface to indicate to the java.lang.Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

Invoking Object’s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See java.lang.Object.clone() for details on overriding this method.

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

Since:

JDK1.0

Version:

1.17, 11/17/05

Author:

unascribed

See Also:

java.lang.CloneNotSupportedException

java.lang.Object.clone()

意思就是:

此类实现了 Cloneable 接口,以指示 Object.clone() 方法可以合法地对该类实例进行按字段复制。

如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常。

按照惯例,实现此接口的类应该使用公共方法重写 Object.clone(它是受保护的)。请参阅 Object.clone(),以获得有关重写此方法的详细信息。

注意,此接口不 包含 clone 方法。因此,因为某个对象实现了此接口就克隆它是不可能的。即使 clone 方法是反射性调用的,也无法保证它将获得成功。

我们平时需要对某个对象进行操作,但是这个对象被两个地方操作,却都要使用最原始时候的对象。这个时候就需要Cloneable接口出现了。并且如果我们对象里面的属性还有非基本类型对象的话也需要实现此接口直到没有属性是非基本类型对象为止(深拷贝)

这里有个不错的例子:http://cqitcs02370236.cnblogs.com/archive/2006/04/23/382644.html

2

2

分享到:

2010-04-23 13:46

浏览 5671

评论

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/184076.html原文链接:https://javaforall.cn