The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Cloneable: How an old Bug can bite for a very long time

Posted by schaefa on October 12, 2004 at 5:15 PM PDT

I cannot remember when I complained about the missing public Object clone() method in the java.lang.Cloneable interface for the first time but in the latest release of Java (1.5) this bug hurts us developers even more.

Assume we want to create our very own list that allows deep copies when cloned. In 1.5 the code could look like this (disclaimer: I am not a 1.5 expert so bare with me if the syntax if wrong):

ArrayList<Cloneable> myCloneableList = new ArrayList<Cloneable>();
ArrayList<Cloneable> myDeepCopiedList = (ArrayList<Cloneable>)
      myCLoneableList.clone(); // Assuming the method is overwritten and public
Now the clone() method could look like this (if the problem would have been fixed):
public Object clone() {
   // Create the list here
   lNewList = new ArrayList<Cloneable>();
   Iterator i = getIterator();
   while(i.hasNext()) {
      lNewList.add(((Cloneable) i.next()).clone());
   }
   return lNewList;
}
But this does not work and the only way to make it work is to use reflection to get the clone() method, check that the method is overwritten and public and then call it. So my fellow JDK developers at Sun can you please explain to me why this is still such a hassle and nobody dared to fix it (JDK 1.0 was released more than 7 years ago)? Now with the generic types that bug is going to haunt us even more.

Happy coding - Andy
Comments
Comments are listed in date ascending order (oldest first)