Java报错”CloneNotSupportedException”的原因以及解决办法

  • Post category:Java

当一个类没有实现Cloneable接口而调用Object类中的clone()方法时,就会抛出CloneNotSupportedException异常。

类实现Cloneable接口表明该类可以被克隆。

解决方案如下:

  1. 实现Cloneable接口和重写Object类中的clone()方法。

例如,我们有以下Person类:

public class Person implements Cloneable {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 重写clone()方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    // getter和setter方法
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

现在我们可以实例化该类并调用clone()方法进行克隆:

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Tom", 25);
        try {
            Person p2 = (Person) p1.clone();
            System.out.println(p1.getName() + " " + p1.getAge());
            System.out.println(p2.getName() + " " + p2.getAge());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

输出结果如下:

Tom 25
Tom 25
  1. 使用序列化实现深克隆。
import java.io.*;

public class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 通过序列化和反序列化实现深克隆
    public Object deepClone() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(this);
        ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(bo.toByteArray()));
        return oi.readObject();
    }

    // getter和setter方法
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

现在我们可以实例化该类并调用deepClone()方法进行深克隆:

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Tom", 25);
        Person p2;
        try {
            p2 = (Person) p1.deepClone();
            System.out.println(p1.getName() + " " + p1.getAge());
            System.out.println(p2.getName() + " " + p2.getAge());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

输出结果如下:

Tom 25
Tom 25