java -- 禁止对象clone

来源:互联网 发布:java try是干什么的 编辑:程序博客网 时间:2024/05/17 00:40
/**Copyright (c) 2016, gp.inc and/or its affiliates. All rights reserved.*/package thinkingInJava.thinkingInJava;public class Ordinary {}class WrongClone extends Ordinary {    public Object clone() throws CloneNotSupportedException {        return super.clone();    }}class IsCloneable extends Ordinary implements Cloneable {    public Object clone() throws CloneNotSupportedException {        return super.clone();    }}class NoMore extends IsCloneable {    public Object clone() throws CloneNotSupportedException {        throw new CloneNotSupportedException();    }}class TryMore extends NoMore {    public Object clone() throws CloneNotSupportedException {        return super.clone();    }}class BackOn extends NoMore {    private BackOn duplicate(BackOn b) {        return new BackOn();    }    public Object clone() {        return duplicate(this);    }}final class ReallyNoMore extends NoMore {}
/**Copyright (c) 2016, gp.inc and/or its affiliates. All rights reserved.*/package thinkingInJava.thinkingInJava;public class TestOrdinary {    static Ordinary tryToClone(Ordinary ord) {        String id = ord.getClass().getName();        Ordinary x = null;        if (ord instanceof Cloneable) {            try {                System.out.println("attempting " + id);                x = (Ordinary) ((IsCloneable) ord).clone();                System.out.println("cloned " + id);            } catch (CloneNotSupportedException e) {                System.out.println("could not clone " + id);            }            System.out.println("");        }        return x;    }    public static void main(String[] args) {        Ordinary[] ord = { new IsCloneable(), new WrongClone(), new NoMore(), new TryMore(), new BackOn(),                new ReallyNoMore(), };        Ordinary x = new Ordinary();        for (int i = 0; i < ord.length; i++) {            tryToClone(ord[i]);        }    }}

这里写图片描述

1 0
原创粉丝点击