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

后端 未结 7 2032
情书的邮戳
情书的邮戳 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:44

    As everyone else has said, this simply isn't possible. If it's cleaning up resources you're after, then you might consider using a pattern such as:

    class A {
    
        private boolean cleanedUp;
    
        public void cleanUp() {
            // clean up any resources
            cleanedUp = true;
        }
    
        public boolean isCleanedUp() {
            return cleanedUp;
        }
    }
    

    And then using it like so:

    A a = new A();
    a.cleanUp();
    if (a.isCleanedUp()) {
        ...
    }
    

    A better solution might be to implement the java.io.Closeable or java.lang.AutoCloseable interfaces depending on your circumstance:

    class B implements AutoCloseable {
    
        private boolean closed;
    
        public boolean isClosed() {
            return closed;
        }
    
        @Override public void close() throws Exception {
            // clean up any resources
            closed = true;
        }
    }
    

    In which case you can use a try-with-resources statement:

    try (B b = new B()) {
        // do stuff
    } catch (Exception ex) {
        // oh crap...
    }
    

    Or you could even combine the two and do it that way, whichever you prefer.

    Or lastly you could do it the way William Morrison explained (though I'd probably cheat and just use java.util.concurrent.atomic.AtomicReference instead of making my own class, and it comes with the added benefit of being a generified type), which, depending on your circumstance, may really be unnecessary. After all, you could always just do (even though it might seem a little odd):

    A a = new A();
    
    a.doStuffAndDisappear();
    a = null;
    
    if(a == null){
         //...
    }
    

提交回复
热议问题