// references/CheckCloneable.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.// Check to see if a reference can be cloned// Can't clone this -- doesn't override clone():class Ordinary {}// Overrides clone, doesn't implement Cloneable:class WrongClone extends Ordinary {@Override public Object clone()throws CloneNotSupportedException {return super.clone(); // Throws exception}}// Does all the right things for cloning:class IsCloneable extends Ordinaryimplements Cloneable {@Override public Object clone()throws CloneNotSupportedException {return super.clone();}}// Turn off cloning by throwing the exception:class NoMore extends IsCloneable {@Override public Object clone()throws CloneNotSupportedException {throw new CloneNotSupportedException();}}class TryMore extends NoMore {@Override public Object clone()throws CloneNotSupportedException {// Calls NoMore.clone(), throws exception:return super.clone();}}class BackOn extends NoMore {private BackOn duplicate(BackOn b) {// Somehow make a copy of b and return that// copy. A dummy copy, just to make a point:return new BackOn();}@Overridepublic Object clone() {// Doesn't call NoMore.clone():return duplicate(this);}}// You can't inherit from this, so you can't// override clone() as you can in BackOn:final class ReallyNoMore extends NoMore {}public class CheckCloneable {public staticOrdinary tryToClone(Ordinary ord) {String id = ord.getClass().getName();System.out.println("Attempting " + id);Ordinary x = null;if(ord instanceof Cloneable) {try {x = (Ordinary)((IsCloneable)ord).clone();System.out.println("Cloned " + id);} catch(CloneNotSupportedException e) {System.out.println("Could not clone " + id);}} else {System.out.println("Doesn't implement Cloneable");}return x;}public static void main(String[] args) {// Upcasting:Ordinary[] ord = {new IsCloneable(),new WrongClone(),new NoMore(),new TryMore(),new BackOn(),new ReallyNoMore(),};Ordinary x = new Ordinary();// This won't compile because// clone() is protected in Object://- x = (Ordinary)x.clone();// Checks first to see if the class// implements Cloneable:for(Ordinary ord1 : ord) {tryToClone(ord1);}}}/* Output:Attempting IsCloneableCloned IsCloneableAttempting WrongCloneDoesn't implement CloneableAttempting NoMoreCould not clone NoMoreAttempting TryMoreCould not clone TryMoreAttempting BackOnCloned BackOnAttempting ReallyNoMoreCould not clone ReallyNoMore*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。