I have to clone an object multiple times. My object is non serializable. I am using the following function
@SuppressWarnings("unchecked")
public static T cloneThroughJson(T t) {
Gson gson = new Gson();
String json = gson.toJson(t);
return (T) gson.fromJson(json, t.getClass());
}
// ...
Object cloned = cloneThroughJson(someObject);
I found that this is returning every time reference to the same object. e.g
Let's say I first call it for cloneThroughJson(x)
it returns Y
I again call it in the same function cloneThroughJson(x)
. And it again returns Y
.
Do you know how to clone non serializable object in java using deep cloning?
It seems that it is a known issue. Your method will ONLY work if the copied object has a default no-argument constructor. In order to achieve what you want - you need to create an instance creator.
From documentation:
While deserializing an Object, Gson needs to create a default instance of the class Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor Doesn't matter whether public or private Typically, Instance Creators are needed when you are dealing with a library class that does NOT define a no-argument constructor
Instance Creator Example
private class MoneyInstanceCreator implements InstanceCreator<Money> { public Money createInstance(Type type) { return new Money("1000000", CurrencyCode.USD); } }
Type could be of a corresponding generic type
- Very useful to invoke constructors which need specific generic type information
- For example, if the Id class stores the class for which the Id is being created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With