I am constructing a framework where I need to make copies of objects at runtime and I do not want to force those object classes to implement any interface, like Cloneable, or Prototype pattern, or anything else.
So, for that purpose I was planning to efficiently clone those objects using the functionality of sun.misc.Unsafe
and its methods: allocateInstance(Class cls)
and copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes)
. But I cannot find any way to get the size of an object in bytes in the heap space.
I know that I can use reflection and copy from field to field. But that is not no efficient. Do you know any manner of getting the size of an object in the heap? Or any other way of efficiently copying an object?