Java, executing a method when object's scope ends

后端 未结 5 1245
庸人自扰
庸人自扰 2021-02-12 20:48

I\'ve an object with a certain state. The object is passed around and it\'s state is temporarly altered. Something like:

public void doSomething(MyObject obj) {
         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-12 20:51

    Short answer: No.

    Medium answer: The best practice in this situation is to use a try ... finally block.

    Longer answer: C++ doesn't really give you this either: C++ destructors are run on de-allocation. If you fail to deallocate an object and all references to it fall out of scope, the destructor will not be called.

    As an aside, if garbage collection in Java was reference counting, then finalizers would implement exactly this behaviour.

提交回复
热议问题