I have found myself wanting to do certain things in my programs only if a variable has changed. I have so far been doing something like this:
int x = 1;
in
another way is use AOP to intercept changing of fields, AspectJ for example, you could have a look a http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html
you can also use flag concept, as when ever changing the value of x . assign true for an boolean variable. Keep boolean with default value as false. check by this way.
This way is better than having getters and setters in base of performance, not to have reduntant code of two methods getters and setters.
You can use getter/setter with dirty bit associated with each field. mark it dirty if the value is changed through setter, and force user to use setters
Assuming you have multiple threads you could create an object monitor and wait for the changed object to wake all blocked threads.
Something like this:
private MyObject myObject;
... other thread ...
while(true) {
myObject.wait()
logic you want to run when notified.
}
... other thread ...
... later on ...
myObject.change();
myObject.notifyAll();
Example:
create a variable with the same name with a number.
int var1;
int var2;
if(var1 != var2)
{
//do the code here
var2 = var1;
}
hope this help.
Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:
public class X
{
private int x = 1;
//some other code here
public void setX(int proposedValueForX)
{
if(proposedValueForX != x)
{
doOneTimeTaskIfVariableHasChanged();
x = proposedValueForX;
}
}
}