Java之CloneNotSupportedException

来源:互联网 发布:arm linux gcj 编辑:程序博客网 时间:2024/04/27 16:07

如果在没有实现Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常。


public class Test {        public static void main(String args[]) {              Employee e = new Employee();      Employee ee = e.clone();    } }class Employee {         @Override    protected Employee clone() {         Employee clone = null;         try{             clone = (Employee) super.clone();          }catch(CloneNotSupportedException e){             throw new RuntimeException(e); // won't happen         }                 return clone;     }}



如上述例子所示,Employee没有实现Cloneable接口,main方法运行时将抛出CloneNotSupportedException异常。

只要将Employee实现Cloneable接口就不会出现异常。


public class Test {        public static void main(String args[]) {              Employee e = new Employee();      Employee ee = e.clone();    } }class Employee implements Cloneable{         @Override    protected Employee clone() {         Employee clone = null;         try{             clone = (Employee) super.clone();          }catch(CloneNotSupportedException e){             throw new RuntimeException(e); // won't happen         }                 return clone;     }}

如果对象的类不支持 Cloneable 接口,则重写 clone 方法的子类也会抛出此异常,以指示无法复制某个实例。



作者:zhuhao717

微博:http://weibo.com/336765659

博客:http://blog.csdn.net/zhuhao717(转载请说明出处)



0 0
原创粉丝点击