Is it possible to set an Object to be null from within itself?

后端 未结 7 2025
情书的邮戳
情书的邮戳 2021-02-07 07:06

I know that this = null is illegal.

I\'m wondering if there\'s some other way to have an object clean itself up.

my desire is to be able to do some

7条回答
  •  误落风尘
    2021-02-07 07:47

    I might be missing something but, since you mention that:

    I'm wondering if there's some other way to have an object clean itself up.

    And:

    I have a self contained Widget that would be improved considerably if it could just make itself null after doing what it needs to do. Thus letting the GC clean it up and not leaving the Widget's user to have to set it to null manually.

    How about, not keeping a reference to the object at all?

    new A().doStuffAndDisappear();
    // no reference, instance of A is eligible to GC
    

    Update

    Since this is not what the OP is looking for, let me expand @Perce solution:

    interface AHolder 
    {
        void setA(A a);
    }
    
    class AParent implements AHolder {
    
        private A a;
    
        public AParent() {
            a = new A();
        }
    
        public void doSomething() {
            a.doStuffAndDisappear(this);
            if(a == null)
            {
                System.out.println("It is true!");
            }
        }
    
        public void setA(A a) {
            this.a = a;
        }
    }
    
    class A 
    {
        void doStuffAndDisappear(AHolder parent) {
            parent.setA(null);
        }
    }
    

    Now you don't need to know the type of the parent or the field that holds A.

    Working Example.


    If you want to make A null its reference at every parent, just change A to hold a list of parents (List parents), and implement a method to track parents:

    void addParent(AParent parent)
    {
        parents.add(parent);       
    }
    

    Plus a void cleanUp() which iterate over its parents setting null:

    void cleanUp()
    {
        for (AParent parent : parents)
        {
            parent.setA(null);         
        }   
        parents.clear();  
    } 
    

    Notice how this solution looks a lot like JavaBeans Bound Properties... This is not by coincidence; we are, in a way, creating a simple Event / Listener architecture to that A can notify its parents to get ride of their reference to it.

提交回复
热议问题