如何在类中将实例设置为null?

如何在类中将实例设置为null?

问题描述:

我想在我的课程中创建一个 release()方法。
在调用 release()之后,如何将该实例设置为 null

I want to create a release() method in my class. After calling release(), how can I set that instance to null?

我的意思是:

I mean this:

ABC abc = new ABC();
abc.release();
if(abc == null) Log.d("That's what I want");

然后我想检查 abc
如何做到这一点?

then I want to check if abc is null. How do I do this?

您不必从每个实例的内部执行此操作。如果您删除了此对象的引用( all 引用),那么当垃圾收集器下一次执行循环时,它将自动删除。

You don't have to do this from inside the instance per sé. If you remove the reference (all references) to this object then it will be automatically removed the next time the garbage collector does his rounds.

简单地做

ABC abc = new ABC(); // Create new instance and reference it with variable abc
abc = null; // remove the reference from abc; the instance is now floating around in space

您可以尝试使用 System.gc( ) 。最后,我记得读到这只是一个迹象,表明你想要一个GC而不是一个实际的力量,但文档只是说它'运行垃圾收集器'。

You can try to explicitly call the garbage collector using System.gc(). Last I remember reading is that this is merely an indication that you would like a GC and not an actual force but the documentation just says it 'runs the garbage collector'.