天天看點

java cloneable_JAVA基礎 對象克隆 實作java.lang.Cloneable接口

先來看看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

分享到:

java cloneable_JAVA基礎 對象克隆 實作java.lang.Cloneable接口
java cloneable_JAVA基礎 對象克隆 實作java.lang.Cloneable接口

2010-04-23 13:46

浏覽 5671

評論