如何在类中将实例设置为null? [英] How to set the instance to null inside class?

查看:183
本文介绍了如何在类中将实例设置为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'.

这篇关于如何在类中将实例设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆