Java克隆抽象对象
发布时间:2020-12-15 00:21:59 所属栏目:Java 来源:网络整理
导读:我想知道有没有办法做以下事情.我有一个抽象类,Shape和其所有不同的子类,我想覆盖克隆方法.所有我想要做的方法是从当前的toString()创建一个新的Shape.显然,我不能做以下,因为Shape是抽象的.有另一种方法来做,因为每个子类中的覆盖克隆只是为了简单的名称更
我想知道有没有办法做以下事情.我有一个抽象类,Shape和其所有不同的子类,我想覆盖克隆方法.所有我想要做的方法是从当前的toString()创建一个新的Shape.显然,我不能做以下,因为Shape是抽象的.有另一种方法来做,因为每个子类中的覆盖克隆只是为了简单的名称更改似乎是无用的.
public abstract class Shape { public Shape(String str) { // Create object from string representation } public Shape clone() { // Need new way to do this return new Shape(this.toString()); } public String toString() { // Correctly overriden toString() } } 解决方法
你可以尝试使用反射:
public abstract class AClonable implements Cloneable{ private String val; public AClonable(){ } public AClonable(String s){ val=s; } public String toString(){ return val; } @Override public AClonable clone(){ try { System.out.println(getClass().getCanonicalName()); AClonable b= getClass().getDeclaredConstructor(String.class).newInstance(val); return b; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } 在clone()方法中调用getClass().因为ACloneble是抽象的,所以会打电话到具体的类. public class ClonebaleOne extends AClonable{ public ClonebaleOne(){ super(); } public ClonebaleOne(String s) { super(s); // TODO Auto-generated constructor stub } } 和 public class ClonebaleTwo extends AClonable{ public ClonebaleTwo(){ super(); } public ClonebaleTwo(String s) { super(s); // TODO Auto-generated constructor stub } } 最后 public static void main(String[] args){ AClonable one = new ClonebaleOne("One"); AClonable tow= new ClonebaleTwo("Two"); AClonable clone = one.clone(); System.out.println(clone.toString()); clone = tow.clone(); System.out.println(clone.toString()); } 输出: ClonebaleOne One ClonebaleTwo Two 但它比解决方案更是一个黑客 [编辑]我的两个克隆比…快) [编辑]要完成clone()的另一个含义可以是 @Override public AClonable clone(){ try { ByteArrayOutputStream outByte = new ByteArrayOutputStream(); ObjectOutputStream outObj = new ObjectOutputStream(outByte); ByteArrayInputStream inByte; ObjectInputStream inObject; outObj.writeObject(this); outObj.close(); byte[] buffer = outByte.toByteArray(); inByte = new ByteArrayInputStream(buffer); inObject = new ObjectInputStream(inByte); @SuppressWarnings("unchecked") Object deepcopy = inObject.readObject(); inObject.close(); return (AClonable) deepcopy; } catch (Exception e) { e.printStackTrace(); } return null; } 当你的抽象类实现Serialazable.在那里,您将您的对象写入光盘,并创建具有光盘值的副本. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |