gpt4 book ai didi

java - 为什么对我的实例的静态引用不更新内部值?

转载 作者:行者123 更新时间:2023-12-02 01:32:13 25 4
gpt4 key购买 nike

我有一段相对复杂的代码,它使用 Gson 序列化对象,以便为它们保存非常具体的值。除此之外,还有一个特定的对象控制着代码的相当大的部分,并且它的访问非常频繁,因此为了减少不必要的列表管理来查找它(这些配置对象存储在列表中),我创建了一个静态引用更快地访问它,但它似乎不适用于该对象。

我已经简化了代码,但这里的关系让我感到困惑。如果我使用下面的代码,active 将不会更新对 this 的静态引用:

public static void main(String[] args) {
String json = "{ \"active\": false }";
final MyObject myObject = new MyObject();
final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

myObject.fromGson(gson.fromJson(json, MyObject.class));
for (int i = 0; i < 10; i++) {
myObject.setActive(!myObject.isActive());
}
}

private static class MyObject {
@Expose private boolean active;
private static MyObject self;

public MyObject() {
this.active = false;
self = this; // notice where this line is located
}

public static boolean active() {
return self.isActive();
}

public boolean isActive() {
return active;
}

public void setActive(boolean active) {
this.active = active;

System.out.println("this: " + this.isActive());
System.out.println("self: " + self.isActive());
}

public void fromGson(MyObject object) {
this.setActive(object.isActive());
}
}

测试时,输出:

this: false
self: false
this: true
self: false
this: false
self: false
this: true
self: false
this: false
self: false
this: true
self: false
this: false
self: false
this: true
self: false
this: false
self: false
this: true
self: false
this: false
self: false

显然,self 没有改变,尽管它应该只是访问 this.isActive()。现在考虑以下更改:

public MyObject() {
this.active = false;
}

public void fromGson(MyObject object) {
self = this; // notice the new position
this.setActive(object.isActive());
}

突然,在测试该程序时,我得到:

this: false
self: false
this: true
self: true
this: false
self: false
this: true
self: true
this: false
self: false
this: true
self: true
this: false
self: false
this: true
self: true
this: false
self: false
this: true
self: true
this: false
self: false

这是怎么回事?为什么 Gson 完成序列化后初始化 self 会改变一切? gson 是这里的错吗?就代码而言,我指向相同的 this 引用,那么发生了什么?即使解决方案是将其移至 fromGson,那么在没有任何内容可反序列化的情况下(如果配置不存在,这可能会发生在我的原始代码中),它不会不调用fromGson

最佳答案

实际上,正如 @MadProgrammer 提到的,由于 Gson,我对 static 的引用被强制改变了。由于 Gson 序列化了该值,因此我对 self = this 的引用被修改为来自 Gson#fromJson 的反序列化 MyObject

为了避免这种情况,我添加了一个空检查(就我个人而言,我无论如何都不喜欢这种静态关系动态,并且可能会废弃它):

private static MyObject self = null;

public MyObject() {
this.active = false;
if (self == null) { // prevents Gson from messing with it later on
self = this;
}
}

关于java - 为什么对我的实例的静态引用不更新内部值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57548815/

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