eBe*_*ani 5 java garbage-collection
是否可以将类中的类的实例设置为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;
}
}
Run Code Online (Sandbox Code Playgroud)
我试过这个并没有用.使用"this = null"我得到左侧需要变量的错误.有没有办法实现类似的东西?
对象的实例不知道哪些引用可能引用它,因此对象中的代码无法使这些引用无效.你要求的是不可能的(*).
*至少不是没有添加一堆脚手架来跟踪所有参考,并以某种方式通知他们的主人他们应该被取消 - 绝不会是"为了方便".