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
Cloneableand therefor the public methodclone(). - Through reflection call foo.clone() (to reach the protected method
Object.clone()). It throwsCloneNotSupportedExceptionbecausefoo‘s class does not implementCloneable. - Serializing and deserializing foo: I need a shallow copy, not a deep copy.
Limitations:
foo‘s class is not know at compile time.foomight 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.
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).