如何通过自己的类删除对象?

She*_*lef 1 java null garbage

我知道如何通过将其引用变量设置为null来为垃圾收集器留下信号以删除对象:

Player player_reference = new Player();
player_reference = null; 
// Now the Garbage collector knows to release all the memory related to this object.
Run Code Online (Sandbox Code Playgroud)

但是如何通过对象的类将引用变量设置为null?

class Player {
    public void doSomthing() {
        if(condition) {
            // some code which set the reference variable to null.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

我知道如何通过将其引用变量设置为null来为垃圾收集器留下信号以删除对象

这不是一个"信号" - 它只是确保所讨论的变量不会阻止垃圾收集.你真的,真的需要清楚变量,引用和对象之间的差异.这个问题毫无意义:

但是如何通过对象类将引用变量设置为null?

什么参考?可能存在多个变量,这些变量都具有对同一对象的引用的值.或者确实可能没有这样的变量 - 您可以通过一些中间表达式调用该方法:

foo().bar().doSomething();
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您希望将哪个变量设置为null?

当在任何线程中无法再获取垃圾时,该对象将有资格进行垃圾收集.您无需手动删除它,也不需要"发出信号"垃圾收集器.它会自然而然地发生.