JDK1.8源码学习--lang包(Cloneable)

本文介绍了Java中Cloneable接口的作用,它用于标记类允许被克隆。如果不实现此接口,调用Object类的clone方法将抛出CloneNotSupportedException。文章通过示例展示了如何在类中正确实现克隆,并强调了克隆在学习过程中的重要性。
摘要由CSDN通过智能技术生成

前言


月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)

央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)

泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)

月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容

希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!
 

一.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();
        }
    }
}

                运行结果:

二.总结

            克隆是个好东西啊,大家要多用.. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值