Pregunta

My framework handles domain objects of any class. I need to be able to shallow clone such a domain object instance foo, as if it implemented Cloneable (which it doesn't) and I called Object.clone() on it which returns a shallow clone.

Things that do NOT work:

  • Force foo's class to implement Cloneable and therefor the public method clone().
  • Through reflection call foo.clone() (to reach the protected method Object.clone()). It throws CloneNotSupportedException because foo's class does not implement Cloneable.
  • Serializing and deserializing foo: I need a shallow copy, not a deep copy.

Limitations:

  • foo's class is not know at compile time.
  • foo might have field that are not exposed as getters/setters.

Note: there are a couple of similar questions, but none seem to focus on a getting a shallow clone.

¿Fue útil?

Solución

BeanUtils can clone non-cloneable Beans as long as they have setter/getters. Unfortunately Orika bean mapper doesn't support mapping of private fields either.

In the end, it may be easier for you to implement it based on reflection on your own (as hoaz is suggesting), since most libraries for bean mapping try to perform deep copies and you seem to have some special requirements (such as the support for copying private fields).

Otros consejos

class A{
    private int a;
    private int[] b;


    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public int[] getB() {
        return b;
    }
    public void setB(int[] b) {
        this.b = b;
    }

    public static A shallowCopyOf(A instanceOfA){ //performs shallow copy
        A newInstance  = new A();
        newInstance.setA(instanceOfA.getA());
        newInstance.setB(instanceOfA.getB());
        return newInstance;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top