Sie sind auf Seite 1von 3

Object Cloning in Java Show Printable Version Email this Page Subscription Add to Favorites Copy Object Cloning

in Java link Author Recent Articles Similar Articles pradeep ( Team Leader ) Yet to provide details about himself All articles By pradeep Objects in Java are referred using reference types, and there is no direct way t o copy the contents of an object into a new object. The assignment of one reference to another merely creates another reference to t he same object. Therefore, a special clone() method exists for all reference typ es in order to provide a standard mechanism for an object to make a copy of itse lf. Here are the details you need to know about cloning Java objects. Why create a local copy? The most probable reason for creating a local copy of an object is because you p lan to modify the object, and you don't want to modify the method caller's objec t. If you decide that you need a local copy, you can perform the operation by us ing the clone() method of the Object class. The clone() method is defined as pro tected, but you must redefine it as public in all subclasses that you might want to clone. For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this: Code: Java import java.util.*; class MyInt { private int i; public MyInt(int ii) { i = ii; } public void increment() { i++; } public String toString() { return Integer.toString(i); } } public class Test { public static void main(String[] args) {

ArrayList al = new ArrayList(); for(int i = 0; i < 10; i++ ) al.add(new MyInt(i)); ArrayList al1 = (ArrayList)al.clone(); // Increment all al1's elements: for(Iterator e = al1.iterator(); e.hasNext(); ) ((MyInt)e.next()).increment(); } } The clone() method produces an Object, which must be recast to the proper type. This example shows how ArrayList's clone() method does not automatically try to clone each of the objects that the ArrayList contains -- the old ArrayList and t he cloned ArrayList are aliased to the same objects. This is often called a shal low copy, since it's only copying the "surface" portion of an object. The actual object consists of this "surface," plus all the objects that the references are pointing to and all the objects those objects are pointing to, etc. This is oft en referred to as the "Web of objects." When you copy the entire mess, it is cal led a deep copy. The Cloneable interface and deep copies By default, classes in Java do not support cloning; the default implementation o f the clone() method throws a CloneNotSupportedException. You should override im plementation of the clone() method. Remember that you must make it public and, i nside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default i mplementation of Object.clone only performs a shallow copy, classes must also ov erride clone to provide a custom implementation when a deep copy is desired. Bas ically, if you want to make objects of your class publicly cloneable, you need c ode like this: Code: Java class Test implements Cloneable { ... public Object clone() { try { return super.clone(); } catch( CloneNotSupportedException e ) { return null; } } ... } If you are happy with a protected clone, which just blindly copied the raw bits of the object, you don't need to redefine your own version. However, you will us ually want a public one. (Note: You can't create a private or default scope clon e; you can only increase the visibility when you override.) Possible problems and a solution

Since the clone() method is protected, subclasses have to explicitly agree to be cloneable by overriding this protected method with a public method. All of the Collections classes do this. The subclass also has to implement Cloneable for th e default cloning mechanism in Object.clone() to work. If you have an object that you know has a public clone() method, but you don't k now the type of the object at compile time, you have problems. For instance, say x is declared as an Object. You can't just call x.clone() because Object.clone( ) is protected. If Cloneable defined a public clone() method, you could use ((Cl oneable) x).clone(), but it doesn't. You either have to enumerate all the classe s that you think x could be, or you have to resort to reflection. Another problem arises when you try deep copying of a complex object. You're ass uming that the clone() method of all member object variables also does deep copy ; this is too risky of an assumption. You must control the code in all classes, or you must know that all classes involved in deep copy operation do such a copy in the right way. One solution to these problems is to clone using serialization. Serialization is usually used to send objects off somewhere (such as into a file or over the net work) so that somebody else can reconstruct them later. You can abuse serializat ion to immediately reconstruct the object yourself. If the object is serializabl e at all, the reconstruction should be a faithful copy. In normal uses of serial isation, the original object is nowhere near a faithful copy; it could be on the other side of the world at the far end of a network connection. You can be sure that changing the copy will have no effect on the original.

Das könnte Ihnen auch gefallen