美文网首页
【JAVA】标记接口Cloneble用法

【JAVA】标记接口Cloneble用法

作者: 李翾 | 来源:发表于2019-11-07 13:11 被阅读0次

    最经典的标记接口,Cloneble,看下源码如下:
    public interface Cloneable {
    }
    看完有何感想,是不是很诧异,怎么什么都没有,当然什么都没有,它只是个标记,除此之外没有其他意义,那接下来看这个标记的意义,如下:
    protected Object clone() throws CloneNotSupportedException {
    if (!(this instanceof Cloneable)) {
    throw new CloneNotSupportedException("Class " + getClass().getName() +
    " doesn't implement Cloneable");
    }

        return internalClone();
    }
    

    看完是不是豁然开朗,判断条件this instanceof Cloneable,判断是不是实现了Cloneable接口,否则报异常,所以我们在让类实现Cloneable接口就好了。

    相关文章

      网友评论

          本文标题:【JAVA】标记接口Cloneble用法

          本文链接:https://www.haomeiwen.com/subject/frpigxtx.html