【发布时间】:2019-12-27 15:53:21
【问题描述】:
我无法弄清楚为什么使用 Gson 将以下对象保存到 .json 文件会引发 StackOverflowError。我在某处有循环引用吗?
这是我试图用 Gson 保存的对象:
public class LocationConfig {
private HashSet<Warp> warps = new HashSet<>();
public LocationConfig() {
warps.add(new Warp("placeholder", false, new Location(Bukkit.getWorld("world"), 0, 0, 0)));
}
// getter and setter
}
LocationConfig 类在其 HashSet warps 中使用以下 Warp 类:
public class Warp {
private String name;
private boolean ifListed;
private Location loc;
public Warp(String name, boolean ifListed, Location loc) {
this.name = name;
this.ifListed = ifListed;
this.loc = loc;
}
// getter and setter
}
我正在使用以下内容来保存LocationConfig 对象:
// config is an object of the type LocationConfig
if (config != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (FileWriter writer = new FileWriter(path)) {
gson.toJson(config, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
我在执行gson.toJson(config, writer)时遇到的错误:
[16:12:42] [Server thread/WARN]: java.lang.StackOverflowError
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:383)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:378)
repeating very often
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:158)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
[16:12:42] [Server thread/WARN]: at com.google.gson.Gson.getAdapter(Gson.java:423)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
[16:12:42] [Server thread/WARN]: at com.google.gson.Gson.getAdapter(Gson.java:423)
repeating very often
谢谢!
【问题讨论】:
-
您的
Location类是否包含对Warp的引用?你也能描述一下Location吗? -
@AdwaitKumar
Location绝对不包含对 Warp 的引用。Location包含双精度 (x,y,z)、一个描述方向的向量和一个 World 对象(也不以任何方式引用Warp)。 -
可能包含对配置的引用
-
@KarimSNOUSSI 不要
LocationConfig。 -
location 是否有这个或者那个暴露整个类引用树是个好主意。喜欢
Location、World。也许可能的循环引用无论如何都与任何显示的类无关。也许它是在其他一些课程之间。那么,可能的回答者如何重现这个问题呢?