Dear Mike ! Thank you for excelent explanation of deep cloning, i liked how you explained with "mistakes" of not implementing Cloneable, so that other users can see which mistakes can appear on the way of deep cloning. 👍
Hi, thank you for the excellent video! There's only one thing I can't understand. If I have to clone a class that extends a library class (for example I have piece, created by me, that extends Rectangle by JavaFX), how can I clone that class?
A way I've done this is to serialize the entire object to a JSON string using Jackson objectMapper. I then deserialize it into into a new object using that JSON string. It's maybe a little expensive, but it is actually pretty universal code that doesn't require me to pollute my model classes. This code: import com.fasterxml.jackson.databind.ObjectMapper; .... public static T clone(Object object, Class clazz) { ObjectMapper objectMapper = new ObjectMapper(); T deepCopy = null; try { deepCopy = objectMapper .readValue(objectMapper.writeValueAsString(object), clazz); } catch (JsonProcessingException e) { e.printStackTrace(); } return deepCopy; }
@@MikesTechCorner I think it kinda depends on the project. If performance is important or if we're paying for cloud resources, then I'd probably pay more attention to saving / squeezing out as much performance as possible. If I was working on a solo project, I'd probably use what's shown in this video. However, I think the utility of the method I posted above is too convenient for me not to use when working in a team. Having to build out a clone for each class type, and then also having to remember to add it to the classes that use that class seems like an easy thing to forget, making the method shown in this video somewhat error prone to engineers who aren't familiar with what the .clone() is doing for that particular object. That said, maybe that's something that just needs to be watched for by more Sr engineers. I think that what's in this video is the most CORRECT way of doing it, but I also think it has issues with failing 'slowly' if devs don't catch improper use of it. Do you think it's always worth doing it the way in your video? Perhaps mine is too hacky , and does even have some issues of its own (e.g - if classes have @JSONIgnore property, they will not be serialized/deserialized properly).
I was expecting the copy constructor pattern to show up. Also you forgot to mention the issue that arises when there is a cyclical reference between the original class and its captured reference (Spaceship refers to Captain, Captain refers to Spaceship)