[英]CloneNotSupportedException not thrown on calling clone() method on object that does not implement Cloneable interface
I recently started Java programming and according to Java SE API Documentation, the Cloneable interface is implemented to indicate that clone operations on that class are allowed. 我最近开始Java编程,根据Java SE API文档,实现了Cloneable接口,以指示允许对该类进行克隆操作。 If not, then a CloneNotSupportedException is thrown.
如果不是,则抛出CloneNotSupportedException 。 However in a practice session i managed to run a program that cloned a class that does not implement the Cloneable interface and no exception was thrown.
但是,在一次练习中,我设法运行了一个程序,该程序克隆了一个未实现Cloneable接口的类,并且未引发任何异常。 I need to know why the exception was not thrown.
我需要知道为什么未引发异常。 I am using JDK 6 update 45 and latest Eclipse IDE on Windows 7. The following is the code:
我正在Windows 7上使用JDK 6更新45和最新的Eclipse IDE。以下是代码:
package com.warren.project.first;
public class PracticeClass {
//explicit initialisation of PracticeClass Instance Variables
private int fieldOne=1;
private int fieldTwo=2;
private int fieldThree=3;
//setters and getters for instance fields of PracticeClass
public void setField1(int field1){
this.fieldOne=field1;
}
public void setField2(int field2){
this.fieldTwo=field2;
}
public void setField3(int field3){
this.fieldThree=field3;
}
public int getField1(){
return this.fieldOne;
}
public int getField2(){
return this.fieldTwo;
}
public int getField3(){
return this.fieldThree;
}
//This method clones the PracticeClass's instances and returns the clone
@Override
public PracticeClass clone(){
PracticeClass practiceClass= this;
return practiceClass;
}
}
package com.warren.project.first;
public class AppMain {
public static void main(String[] args) {
//Create PracticeClass Object
PracticeClass pc1=new PracticeClass();
//Set its instance fields using setters
pc1.setField1(111);
pc1.setField2(222);
pc1.setField3(333);
//Display Values to screen
System.out.println(pc1.getField1()+" "+pc1.getField2()+" "+pc1.getField3());
//Create clone of PracticeClass object
PracticeClass pc2=pc1.clone();
//Print values from PracticeClass clone object
System.out.println(pc2.getField1()+" "+pc2.getField2()+" "+pc2.getField3());
}
}
This code executes successfully without any exception thrown. 此代码成功执行,没有引发任何异常。 Why isn't the CloneNotSupportedException thrown?
为什么不抛出CloneNotSupportedException ?
In order for CloneNotSupportedException
to be thrown, you must call super.clone()
inside your own clone()
method. 为了引发
CloneNotSupportedException
,必须在自己的clone()
方法内调用super.clone()
。 This method will verify if your class implements Cloneable
此方法将验证您的类是否实现
Cloneable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.