Java, executing a method when object's scope ends

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

提交回复
热议问题