How to destroy object in itself

前端 未结 4 769
再見小時候
再見小時候 2021-02-18 18:05

Is there any solution for destroying current instance of object in itself ?

I am looking for something which looks like:

class KillMe {
    ....
    pub         


        
4条回答
  •  醉梦人生
    2021-02-18 18:44

    Your example of what you want to do demonstrates a lack of understanding of how/when objects are destroyed/cleaned up.

    class KillMe {
        ....
        public void destroy() {
            this.getObject = null //this is only for demonstrate my idea
        }
    }
    

    The call you have there (this.getObject) gets a reference to the current object, and then sets that reference to null (ie, no longer pointing at the current object. It doesn't do anything to the object itself, nor does it change other variables elsewhere in the code that happen to point at the object.

    Consider it this way... variables point at values (objects). Until no more variables point at a given value, that value is kept around (not garbage collected/destroyed). In order to remove all variable references to a value, you need to find all the variables that point at it and point them at something else (ex, null). Realistically, you can't do this (though I suppose nothing is impossible with enough scary reflection and/or bytecode magic ;)

    To think of it another way, if you were able to destroy the value/object itself, what would happen to all the other variables that are currently pointing at it? Do they now point at freed memory, resulting in some Java version of a segfault?

提交回复
热议问题