Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, executing a method when object's scope ends

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) {
    obj.saveState();
    obj.changeState(...);
    obj.use();
    obj.loadState();
}

In C++ it's possible to use the scope of an object to run some code when constructing and distructing, like

NeatManager(MyObject obj) { obj.saveState(); }
~NeatManager() { obj.loadState(); }

and call it like

void doSomething(MyObject obj) {
    NeatManager mng(obj);
    obj.changeState();
    obj.use();
}

This simplifies the work, because the save/load is binded with the scope of NeatManager object. Is it possible to do something like this in Java? Is there a way to call a method when the object goes out of the scope it's been declared in? I'm not talking about finalize() nor "destruction" (garbage collection), I'm interested on the scope.

Thanks

like image 649
AkiRoss Avatar asked Jan 22 '10 14:01

AkiRoss


People also ask

Which is a function that executes automatically when the scope of an object expires?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .

How to call method with object in Java?

The dot ( . ) is used to access the object's attributes and methods. To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main. java).

What is the scope of a method?

"Scope" refers to the areas of your program in which certain data is available to you. Any local variable created outside of a method will be unavailable inside of a method.

What happens to the local variables when the method is exited?

Local variables are created on the call stack when the method is entered, and destroyed when the method is exited.


2 Answers

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.

like image 182
Michael Borgwardt Avatar answered Oct 14 '22 05:10

Michael Borgwardt


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.

like image 20
Jon Skeet Avatar answered Oct 14 '22 03:10

Jon Skeet