在 Java 中,我将如何执行以下操作:
Foo bar = new Foo();
Foo a = bar;
Foo b = bar;
bar = null;//will only set bar to null. want to set value of bar to null rather than the reference to null.
是否可以设置变量bar
、a
和b
(都是对bar
的引用) 仅在访问 bar 时为 null?如果是这样,有人可以解释一下如何做到这一点。
最佳答案
不,这在 Java 中是不可能的。
我稍微解释一下您的代码中发生了什么。
此处 Foo bar = new Foo();
您创建了 Foo
的对象并引用了变量 bar
。
这里 Foo a = bar;
和 Foo b = bar;
你把引用放到变量 a
和 b
。所以你现在有一个对象和三个指向他的变量。
此处 bar = null;
您清除了 bar
变量。因此,您有两个指向对象的变量(a
和 b
)和一个没有引用的变量(bar
)。
关于java - 将对象的所有引用设置为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595957/