前言
月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)
央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)
泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)
月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容
希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!
一.Cloneable的作用:
直接看源码注释(我的翻译可能不太准,如果道友们有更棒的理解,可以留言或者私信)
/**
* 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.
* 1.一个类实现了Cloneable接口,以向 java.lang.Object.clone()方法指示
* 该方法制作该类实例的字段对字段副本是合法的
* <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.
* 2.在未实现 Cloneable接口的实例上调用 Object 的 clone 方法
* 会导致抛出异常 CloneNotSupportedException
* <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.
* 3.按照惯例,实现此接口的类应该使用公共方法覆盖Object.clone受保护的)。
* 有关覆盖此方法的详细信息,请参阅 java.lang.Object.clone()
* <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.
* 4.请注意,此接口不包含clone方法。因此,不能仅仅凭借对象实现了这个接口就克隆一个对象。
* 即使以反射方式调用 clone 方法,也不能保证它会成功
* @author unascribed
* @see java.lang.CloneNotSupportedException
* @see java.lang.Object#clone()
* @since JDK1.0
*/
二.示例:
当类未实现Cloneable接口时,将会抛出异常...
public class CloneableTest {
public static void main(String[] args) {
Test test = new Test();
try {
Object clone = test.clone();
} catch (CloneNotSupportedException e) {
System.out.println("ero....");
}
}
static class Test {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
}
运行结果:
二.总结
克隆是个好东西啊,大家要多用..