Cloneable是一个标记接口,没有任何方法。它仅仅表示,它的实现类能够使用继承自java.lang.Object的clone()方法,进行字段级别的拷贝。
在一个没有实现Cloneable接口的类的实例(instance)上调用clone()方法,会导致抛出CloneNotSupportedException异常。同时,实现了Cloneable接口的类,应该重写clone()方法,并把clone()方法修改为public。由于Cloneable接口并不包含clone()方法,因此,即使某个类实现了Cloneable接口,也无法保证它能正确的克隆一个对象。即使通过反射方式调用clone()方法,也不能保证一定能成功。
Cloneable接口源码:
/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.lang;
/**
* A class implements the <code>Cloneable</code> interface to
* indicate to the {@link java.lang.Object#clone()} method that it
* is legal for that method to make a
* field-for-field copy of instances of that class.
* <p>
* Invoking Object's clone method on an instance that does not implement the
* <code>Cloneable</code> interface results in the exception
* <code>CloneNotSupportedException</code> being thrown.
* <p>
* By convention, classes that implement this interface should override
* <tt>Object.clone</tt> (which is protected) with a public method.
* See {@link java.lang.Object#clone()} for details on overriding this
* method.
* <p>
* Note that this interface does <i>not</i> contain the <tt>clone</tt> 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.
*
* @author unascribed
* @version %I%, %G%
* @see java.lang.CloneNotSupportedException
* @see java.lang.Object#clone()
* @since JDK1.0
*/
public interface Cloneable {
}