Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members  

Copier.java

Go to the documentation of this file.
00001 // file:    Copier.java
00002 // author:  Robert Keller
00003 // purpose: To give a general purpose copy method that will clone if possible,
00004 //          otherwise just return its argument.
00005 
00006 import java.lang.reflect.*;     // to use getMethod() and invoke()
00007 
00008 /**
00009  * Copier exists to provide one static method, maybeClone which makes a clone
00010  * of its argument, or returns the argument itself if not.
00011  */
00012 
00013 class Copier
00014 {
00015 static Class[] noArgs = new Class[0];   // a Class array of size 0
00016 static Object[] args = new Object[0];   // an Object array of size 0
00017 
00018 /**
00019  * Copies an Object, as far as that is possible.
00020  * If the Object implements the Cloneable interface, then returns a Clone of 
00021  * the Object.  Otherwise returns the Object itself.
00022  */
00023 
00024 static Object maybeClone(Object ob)
00025   {
00026   // One cannot apply clone() to any class unless it implements the Cloneable
00027   // interface, which class Object does not.  (It does so as a protected
00028   // method, but we need a public method.)
00029   //
00030   // The only means I could find of implementing a method of the desired
00031   // generality is  to use the "reflection" ideas in java.lang.reflect.  
00032   // These allow one to determine whether there is a method with a specific
00033   // name and arguments of a specific type, to get such a method if there is,
00034   // and to invoke the method on actual arguments.  
00035   // In our case we are interested in whether the clone()
00036   // method exists with no arguments.
00037 
00038   if( ob instanceof Cloneable )
00039     {
00040     try
00041       {
00042       // System.out.println(ob + " is instanceof Cloneable");
00043 
00044       // If Cloneable, clone it.
00045 
00046       return ob.getClass().getMethod("clone", noArgs).invoke(ob, args);
00047       }
00048     catch( Exception e)
00049       {
00050       // System.out.println(ob + " is not instanceof Cloneable");
00051       }
00052     }
00053   return ob;      // If Otherwise just return the argument.
00054   }
00055 }

Generated at Wed Feb 19 23:28:36 2003 for OpenList by doxygen1.2.6 written by Dimitri van Heesch, © 1997-2001