java对象复制的问题

来源:百度知道 编辑:UC知道 时间:2024/06/26 03:16:33
test t1 = new test();
test t2 = null;
try {
t2 = (test)t1.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

报错:
java.lang.CloneNotSupportedException: test
at java.lang.Object.clone(Native Method)
at test.main(test.java:81)

1. 被复制的类需要实现Clonenable接口(不实现的话在调用clone方法会抛出CloneNotSupportedException异常) 该接口为标记接口(不含任何方法)
2. 覆盖clone()方法,访问修饰符设为public。方法中调用super.clone()方法得到需要的复制对象,(native为本地方法)

public class CloneNotSupportedExceptionextends Exception

当调用 Object 类中的 clone 方法复制对象,但该对象的类无法实现 Cloneable 接口时,抛出该异常。

重写 clone 方法的应用程序也可能抛出此异常,指示不能或不应复制一个对象。

以上引自java api 中文文档

因为楼主的test没有实现Cloneable接口..

既然你是复制对象~那你t1.clone();这干嘛。
就这样
test t1 = new test();
test t2 = null;
try {
t2 = (test)t1;
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

这样应该可以的!!

代码语法没有问题 就去实现Cloneable接口吧

这个问题太简单了,你要实现clone的接口,就没问题了!