gpt4 book ai didi

使用 GSON 的 Java 克隆对象

转载 作者:搜寻专家 更新时间:2023-10-31 20:32:44 28 4
gpt4 key购买 nike

我必须多次克隆一个对象。我的对象是不可序列化的。我正在使用以下功能

@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);

我发现每次引用同一个对象时都会返回。例如

假设我首先为 cloneThroughJson(x) 调用它它返回 Y我再次在同一函数 cloneThroughJson(x) 中调用它。它再次返回 Y

你知道如何使用深度克隆在 java 中克隆不可序列化的对象吗?

最佳答案

这似乎是一个已知问题。如果复制的对象具有默认的无参数构造函数,您的方法将有效。为了实现你想要的 - 你需要创建一个实例创建者。

来自 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.

关于使用 GSON 的 Java 克隆对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720948/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com