Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-5101827

Adding a Copyable interface to java.lang

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • 5.0
    • core-libs

      Name: rmT116609 Date: 09/14/2004


      A DESCRIPTION OF THE REQUEST :
      Currently the standard Java way to create a copy of an instance is by invoking the clone method. As previous bug reports show, this method is by many developers considered hard to use because it throws a checked exception which forces you to surround your code with try and catch statements.

      Further more, you can almost always be sure that invoking the clone method will not throw an exception - still, Java forces you to write try and catch statements.

      An earlier bug report requesting that the clone method should be changed to throw an unchecked runtime exception instead have been rejected as being too disruptive. See bug 4220218.

      As a result many developers avoid using the clone method which results in many different practices for copying an instance. Some developers implement their own copy method which creates a clone without throwing an exception and others create constructers which accept an existing instance as an argument and returns a copy.

        To standardize the way we, the Java developers, create instance copies I suggest introducing a java.lang.Copyable interface similar to this:

      interface Copyable<T> {
        T copy();
      }

      This interface can then be implemented by all classes which support copying. Consequently, if a class A implements Copyable<A> it is now possible to create a copy of a using the following line of code:

      A a = anExistingInstanceOfA.copy();



      JUSTIFICATION :
      Currently the only standard alternative is to write the following:

      try {
        A a = anExistingInstanceOfA.clone();
      }
      catch(CloneNotSupportedException exception) {
        //this should never happen since A supports cloning
        assert false;
      }
      (Incident Review ID: 310640)
      ======================================================================

            Unassigned Unassigned
            rmandalasunw Ranjith Mandala (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Imported:
              Indexed: