📜  Java中的 CloneNotSupportedException 示例

📅  最后修改于: 2022-05-13 01:54:47.191000             🧑  作者: Mango

Java中的 CloneNotSupportedException 示例

抛出CloneNotSupportedException表明已经调用类 Object 中的 clone 方法来克隆一个对象,但是该对象的类没有实现Cloneable 接口。

等级制度:

那些覆盖 clone 方法的应用程序也可以抛出这种类型的异常,以表明一个对象不能或不应该被克隆。

句法:

public class CloneNotSupportedException extends Exception

CloneNotSupportedException 示例:

Java
// Java program to demonstrate CloneNotSupportedException
 
class TeamPlayer {
 
    private String name;
 
    public TeamPlayer(String name)
    {
        super();
        this.name = name;
    }
 
    @Override public String toString()
    {
        return "TeamPlayer[Name= " + name + "]";
    }
 
    @Override
    protected Object clone()
        throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
public class CloneNotSupportedExceptionDemo {
 
    public static void main(String[] args)
    {
 
        // creating instance of class TeamPlayer
 
        TeamPlayer t1 = new TeamPlayer("Piyush");
        System.out.println(t1);
 
        // using try catch block
        try {
             
             // CloneNotSupportedException will be thrown
             // because TeamPlayer class not implemented
             // Cloneable interface.
              
            TeamPlayer t2 = (TeamPlayer)t1.clone();
            System.out.println(t2);
        }
 
        catch (CloneNotSupportedException a) {
            a.printStackTrace();
        }
    }
}


输出 :