欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CloneNotSupportedException解决方法

程序员文章站 2022-04-15 18:06:44
...

报错的代码:

public class CloneTest {

    private Integer id;

    public CloneTest(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "CloneTest{" +
                "id=" + id +
                '}';
    }

    public static void main(String[] args) throws CloneNotSupportedException {

        CloneTest cloneTest = new CloneTest(1);
        CloneTest cloneTest1 = (CloneTest)cloneTest.clone();

        System.out.println(cloneTest);
        System.out.println(cloneTest1);

    }

}

原因是该类没有实现Cloneable接口,

修改成如下:

public class CloneTest implements Cloneable {

输出:

CloneTest{id=1}
CloneTest{id=1}