How to use Cloneable type as parameter for Java Generic class

I have a general class that should be able to clone parameter type objects. The following is a very simple example. The compiler claims that clone () of type Object is not displayed.

public class GenericTest<T extends Cloneable>
    {
    T obj;
    GenericTest(T t)
        {
        obj = t;
        }
    T getClone()
        {
        // "The method clone() from the type Object is not visible."
        return (T) obj.clone();
        }
    }

I would prefer the caller to invoke cloning, as there are other things that must happen in order to preserve the integrity of the object. The above code is just an illustration of the noise-free problem of other data that I have to support related to the cloned object.

Is there a way around this, or is this another one of those cases where Java developers consider rationalizing their flaws as the equivalent of a lack?

+3
source share
3 answers

Java-. -

static Method clone = Object.class.getMethod("clone"); 

static public <T extends Cloneable> 
T clone(T obj)
    return (T) clone.invoke(obj);
+2

protected Object, . , (, Object, , ?), , re ( ) , .

clone() , , public.

, , - . MyCloneable, clone(), ; , - , , (, java.util.String java.util.ArrayList), .

, .

+6

POJO . :

public static Object clone(Object o)
{
  Object clone = null;

  try
  {
     clone = o.getClass().newInstance();
  }
  catch (InstantiationException e)
  {
     e.printStackTrace();
  }
  catch (IllegalAccessException e)
  {
     e.printStackTrace();
  }

  // Walk up the superclass hierarchy
  for (Class obj = o.getClass();
    !obj.equals(Object.class);
    obj = obj.getSuperclass())
  {
    Field[] fields = obj.getDeclaredFields();
    for (int i = 0; i < fields.length; i++)
    {
      fields[i].setAccessible(true);
      try
      {
        // for each class/suerclass, copy all fields
        // from this object to the clone
        fields[i].set(clone, fields[i].get(o));
      }
      catch (IllegalArgumentException e){}
      catch (IllegalAccessException e){}
    }
  }
  return clone;
}
0

All Articles