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