将object的所有引用设置为null

rod*_*dit 8 java reference

在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.
Run Code Online (Sandbox Code Playgroud)

是否可以设置变量bar,a并且b(都是引用bar)仅在访问bar时为null?如果是这样,有人可以解释如何这样做.

Pri*_*nce 5

这在Java中是不可能的.你不能设置引用abnull使用bar.

原因 - Java pass by value不是pass by reference.

  • 我不认为这是正确的理由."按值/参考传递"是方法调用的评估策略.这里没有调用方法. (11认同)

Mat*_*wel 5

不,在Java中是不可能的.

我稍微解释一下你的代码中发生了什么.在这里,Foo bar = new Foo();您创建了对象Foo并引用了该变量bar.

在这里Foo a = bar;,Foo b = bar;你把引用放在变量ab.所以你现在有一个对象和三个指向他的变量.

在这里bar = null;你清除bar变量.所以你有两个变量(ab)指向对象,一个变量(bar)没有引用.