简体   繁体   中英

Java public clone interface

Is there anything bad or wrong about creating an interface like this and use it in a place i need to make sure a variable is cloneable?

public interface PublicCloneable<I> {
    public I clone();
}

The are questions in SO related on the fact that the Cloneable interface of java is broken and i don't understand why it isn't implemented like this.

You can. The main problem with creating a new interface is that you can only use this interface on new classes that you create, which explicitly implement this interface. Existing classes in the Java library cannot implement this interface, since you can't change their code. (The interface does not magically apply to existing types.) So it's only useful if you kind of create of create a family of custom classes for all the objects you expect to use, and don't use the standard library classes.

This is fine, but you will have to provide your own cloning logic inside the method.

The idea of java.lang.Cloneable is to mark a class as cloneable and the cloning logic to be handled by the JVM. You don't provide field-by-field cloning with Object.clone()

You can pick another cloning mechanism (or use your interface in combination with another one) from the ones suggested in this answer .

If you want to go with entirely your own implementation of clone() it should be OK. However, if you want to use Object.clone() at some point, I'd recommend

public interface PublicCloneable<I> extends Cloneable {
    public I clone();
}

and inside implementation:

   public static class MyClass implements PublicCloneable<MyClass> {
     public MyClass clone() {
        try {
            return (MyClass)super.clone(); // Or do whatever you need here
        } catch (CloneNotSupportedException e) {
            // Always supported
        }
   }

I was not sure if it compiles, but I tried and it seems ok.

Mileage can vary, of course.

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