是否可以从类本身内部使类无效? [英] Can a class be nullified from within the class itself?

查看:59
本文介绍了是否可以从类本身内部使类无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,此代码有效吗?。

For example, is this code valid?.

class abc{
    int x,y;
    abc(int x,int y){
        this.x=x;
        this.y=y;
        while(true)
            update();
    }

    public void update(){
        x--;
        y--;
        if(y==0)
            this=null;
    }
 }

如果以上内容无效,请说明原因。我需要一类在某些迭代之后不复存在的类。请提出上述方法的替代方案。

If the above is not valid, then please explain why. I am in need of a class that after certain iterations ceases to exist. Please suggest alternatives to the above approach.

推荐答案

否。原因是您不使对象为空。当您说 obj = null; 时,您只需将 null 放入先前保存了对对象引用的变量。

No. The reason is that you do not make object null. When you say obj = null; You just put null to variable that previously hold reference to object. There are probably a lot of other references to the same object.

我认为您想要做的是使对象无效并使其成为垃圾回收,但这是必须的。在班级内部做出决定。如果这是问题所在,建议您参考参考文献。

I think that what you want to do is to kind of invalidate object and make it garbage collected but take this decision inside the class. If this is the problem I'd recommend you to take a look on weak references.

其他可能的解决方案是在Java中实现一种智能引用。您可以创建您的类 SmartReference ,该类将保留对对象的实际引用。该对象应对此智能引用进行回调,并调用其方法 invalidate(),类似于您的语法错误表达式 this = null 。您不必在意不要直接引用此类对象,而只能通过智能引用。

Other possible solution is to implement kind of "smart reference" in java. You can create your class SmartReference that will hold the real reference to the object. The object should hold callback to this smart reference and call its method invalidate() that is something like your syntactically wrong expression this = null. You have to care not to refer to such objects directly but only via smart reference.

唯一的问题是为什么要这样做?。确实,这将导致代码更加复杂和不稳定。想象一下:对象决定使自身无效,因此智能引用持有的引用变为 null 。现在,当尝试使用该对象时,此智能参考的所有持有人都将获得NPE!这正是Java中不存在这种机制并且应用程序程序员无法直接管理内存的原因。

The only question is "why do you want to do this?". Really, this will cause the code to be more complicated and unstable. Imagine: the object decides to invalidate itself, so the reference that "smart reference" is holding becomes null. Now all holders of this smart reference will get NPE when trying to use the object! This is exactly the reason the such mechanism does not exist in java and that application programmer cannot mange the memory directly.

底线:删除所有对象引用,并让GC进行艰苦的工作。相信它。它知道要清理垃圾。

Bottom line: remove all object references and let GC to do its hard job. Trust it. It knows to clean the garbage.

这篇关于是否可以从类本身内部使类无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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