當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java CloneNotSupportedException用法及代碼示例


拋出CloneNotSupportedException表示調用了Object類中的clone方法來克隆一個對象,但該對象的類沒有實現Cloneable接口。

等級製度:

那些重寫克隆方法的應用程序也可以拋出此類異常,以指示對象不能或不應該被克隆。

用法:

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();
        }
    }
}

輸出:



相關用法


注:本文由純淨天空篩選整理自piyushkr2022大神的英文原創作品 CloneNotSupportedException in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。