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
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){
//...
}