简体   繁体   中英

Copy constructor v. implementing Cloneable interface

就“最佳实践”而言,哪种方法适用于创建对象的“深层复制”?

Use a copy constructor. Cloneable is a straight-up API disaster. See Effective Java Item 10 ( Item 11 in the 2nd. ed. ).

Item 11: Override clone judiciously

The Cloneable interface was intended as a mixin interface (item 18) for objects to advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks a clone method, and Object 's clone method is protected. You cannot, without resorting to reflection (Item 53), invoke the clone method on an object merely because it implements Cloneable . Even a reflective invocation may fail, as there is no guarantee that the object has an accessible clone method.

There is nothing wrong with the general idea of a cloneable interface. It is easier than copy constructor for API users .

The problems with Java's Cloneable and Object.clone are not that bad either; they can be overcome with a little effort. And you can always have your own cloneable interface.

Java 8 could fix Cloneable by adding the clone() method with a default implementation

interface Cloneable
    public Object clone() default {  return Cloneables.defaultClone(this); }

not sure they have any plan to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM