Java, executing a method when object's scope ends

后端 未结 5 1250
庸人自扰
庸人自扰 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.

    0 讨论(0)
  • 2021-02-12 21:07

    No, there's nothing like that. The closest you've got is try/finally.

    In C# there's the using statement, which executes a Dispose method at the end:

    using (Stream x = ...)
    {
    } // x.Dispose() is called here, in a finally block
    

    There's a possibility that Java 7 will gain something a bit like this, but I don't think anything's been set in stone yet.

    0 讨论(0)
  • 2021-02-12 21:07

    Java 7 has try-with-resources and you can extend AutoCloseable class to make use of it.

    For Java 6 you may want to see the related question: What is the best way to emulate try-with-resources in Java 6?

    0 讨论(0)
  • 2021-02-12 21:11

    Nope, there's no such thing. The closest is probably a try/finally block:

    try
    {
        obj.changeState(...);
        obj.use();
    }
    finally
    {
        obj.loadState();
    }
    

    This ensures that loadState() gets called even when an Exception is thrown or there's an early return.

    0 讨论(0)
  • 2021-02-12 21:15

    As an additional note, don't be tempted to use the Object.finalize() method, which runs when an object is GC'd, as you have no control over when the object is collected.

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