/** * 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 * @see java.lang.CloneNotSupportedException * @see java.lang.Object#clone() * @since JDK1.0 */ public interface Cloneable { }
我看到有很多类实现了这个接口,但是我刚开始不明白它的意义,我认为没有意义。
这个接口没有任何抽象出来的方法,所以实现它又能怎么样呢?
看源码的注释:如果一个没有实现Cloneable接口的类对象调用了clone(),结果是抛出异常。
所以这个类有意义:是为了辨别是否具有克隆的能力而存在的。
在Java中为什么实现了Cloneable接口,就能调用Object的clone方法? - 知乎 (zhihu.com)
具体参考这个博客。
- Cloneable 接口 方法 java langcloneable接口 方法java nullpointerexception接口java lang annotation annotationformaterror java lang java lang module classformaterror java lang numberformatexception getsystenantnames 20230411 iterable java lang annotation 20230707 java lang nullpointerexception jfinal java lang classcastexception caused java lang classcastexception java lang jsonarray