是否可以将类中的类的实例设置为null

是否可以将类中的类的实例设置为null。 例如,我可以这样做吗?

int main{ //Create a new test object Test test = new Test(); //Delete that object. This method should set the object "test" to null, //thus allowing it to be called by the garbage collector. test.delete(); } public class Test{ public delete(){ this = null; } } 

我试过这个并没有用。 使用“this = null”我得到左侧需要变量的错误。 有没有办法实现类似的东西?

对象的实例不知道哪些引用可能引用它,因此对象中的代码无法使这些引用无效。 你要求的是不可能的(*)。

* 至少不是没有添加一堆脚手架来跟踪所有参考文献,并以某种方式通知他们的主人他们应该被取消 – 绝不会是“为了方便”。

你可以做这样的事情

 public class WrappedTest { private Test test; public Test getTest() { return test; } public void setTest(Test test) { this.test = test; } public void delete() { test = null; } } 

this ”是最后一个变量。 你不能为它分配任何值。

如果要将引用设置为null,则可以执行此操作

 test = null; 

this是对您的类实例的引用。 修改引用变量时,它只修改引用而不修改任何其他引用。 例如:

 Integer a = new Integer(1); Integer b = a; a = new Integer(2); //does NOT modify variable b System.out.println(b); //prints 1 

Is it possible to set to null an instance of a class within the class?.

您不能从同一实例的成员方法执行此操作。 所以, this=null或者那种东西不起作用。

为什么将实例设置为null?

这个问题本身是错误的,我们将引用设置为null而不是实例。 未使用的对象自动在java中收集垃圾。

如果设置test=null它最终将被垃圾收集。

  int main{ //Create a new test object Test test = new Test(); // use the object through test test=null; }