无法理解克隆
我有一个简单的程序来克隆一个对象,我用谷歌搜索了错误“线程“main”java.lang.CloneNotSupportedException中的异常:”,但需要您的帮助来理解该错误,为什么我无法克隆 obj1?
public class Test{
int a;
int b;
public Test(int a , int b){
this.a=a;
this.b=b;
}
public static void main(String[]args) throws CloneNotSupportedException{
Test obj1=new Test(2, 4);
Test obj2=(Test) obj1.clone();
}
}
I have a simple program to clone a object , I googled the error "Exception in thread "main" java.lang.CloneNotSupportedException:" but need your help to understand the error, why am I not able to get clone of obj1?
public class Test{
int a;
int b;
public Test(int a , int b){
this.a=a;
this.b=b;
}
public static void main(String[]args) throws CloneNotSupportedException{
Test obj1=new Test(2, 4);
Test obj2=(Test) obj1.clone();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出现此问题的原因是
Test
类未实现Cloneable
接口。如 API 规范<中所述/a>,要修复此问题,请尝试以下操作:
由于
Cloneable
接口未声明任何方法(它称为 marker 接口,就像Serialized
一样),因此仅此而已去做。现在可以克隆Test
类的实例。但是,默认的克隆机制(即
Object
的克隆机制)可能并不完全是您正在寻找的,并且您可能想要重写clone()
方法。默认情况下是进行浅拷贝,也就是说,您将获得类的一个新的、不同的实例,但两个实例的字段将引用相同的对象!例如:最后一行将修改 c2 和 c2clone,因为它们都指向 c1 的同一个实例。如果您希望最后一行仅修改 c2,那么您必须进行我们所说的深复制。
The problem occurs because the class
Test
doesn't implement theCloneable
interface. As stated in the API specs,To fix, try something like:
Since the
Cloneable
interface declares no methods (it's called a marker interface, just likeSerializable
), there's nothing more to do. The instances of yourTest
class can now be cloned.However, the default cloning mechanism (ie, that of
Object
) might not be exactly what you are looking for, and you might want to override theclone()
method. The default is to make a shallow copy, that is, you will get a new, distinct instance of your class, but the fields of both instances will refer to the same objects! For example:The last line will modify both c2 and c2clone because both point to the same instance of c1. If you want the last line to modify only c2, then you have to make what we call a deep copy.
你必须实现 Cloneable。这是一个标记界面。
你的程序应该是
You have to implement Cloneable. It's a marker interface.
Your program should be