What is the best way if I want to copy a model object in java. Because writing copy() function for a nested object in java becomes a lot of works. I just want to avoid that. As a shortcut I use this approach.
public static <T> T copy(T model, Class<T> tClass) throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final byte[] bytes = objectMapper.writeValueAsBytes(model);
final T copy = objectMapper.readValue(bytes, tClass);
return copy;
}
And use it like this.
final McTrack copy = copy(new McTrack(), McTrack.class);
I have made a Utility function copy() that takes a model object and returns a copy of that. First I serialize the entire object into json and then deserialize it again to make a copy. But I am not sure it really efficient. Is there any better way to copy plain old java objects.