当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。