最经典的标记接口,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接口就好了。
网友评论