How to destroy object in itself

前端 未结 4 751
再見小時候
再見小時候 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

    Java objects live until there are no longer any references to them. Since an object cannot determine how many references there are to itself, an object cannot "destroy itself".

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-02-18 18:58

    The object doesn't have access to the references to it so there's no way to set them to null or something else. An object can only be "destroyed" when the garbage collector comes around and clears out all unreferenced objects.

    That being said, try this:

    public void destroy() {
        System.exit( 0 );
    }
    
    0 讨论(0)
  • 2021-02-18 19:04

    No, objects cannot suicide. Any reference of itself is just a reference.

    To "clear" the object within itself one would just clear all instance variables.

    To "clear" the object outside itself one would set the variable equal to null.

    0 讨论(0)
提交回复
热议问题