JDK-6739113 : Fix Cloneable API in a backwards compatible way
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P5
  • Status: Open
  • Resolution: Unresolved
  • Submitted: 2008-08-20
  • Updated: 2017-05-04
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
The Cloneable API should be fixed, and I believe it can be done in a simple and backwards compatible way. Two things are needed, an interface that extends Cloneable adding a public clone method, and a generic System.clone() method. The System.clone() method would first attempt to use the new interface, and failing that, fall back to using reflection. When using reflection, only public clone() methods would be called, which is the same behavior as before. The Cloneable interface could then be marked as deprecated.  See example in test case section.


JUSTIFICATION :
This would greatly simplfy the usage of Cloneable, which has always caused problems for Java developers.  Library developers have done similar techniques, but since there is no standardized interface, it is not useful when interacting with code outside of the library. For this reason it's important that the JDK address it, and not a library/application developer.

Also, since this preserves the previous behavior, there are no backwards compatibility issues.


---------- BEGIN SOURCE ----------
// Example

public interface PublicCloneable extends Cloneable {
    Object clone() throws CloneNotSupportedException;
}

// On System
public static final <T> T clone(T cloneable) throws CloneNotSupportedException {
    if (! (cloneable instanceof Cloneable))
        throw new CloneNotSupportedException();

    if (cloneable instanceof PublicCloneable)
        return (T) ((PublicCloneable)cloneable).clone();
   
     try {
         return (T) cloneable.getClass().getMethod("clone").invoke(cloneable);
     } catch (Exception e) {
         throw new CloneNotSupportedException();
     }
}
---------- END SOURCE ----------