I can't get from the java documentation if it's possible to listen for a change in object's attribute value. Let's say my object has only one int attribute field. I need to perform an action in the moment, my object changes its state. Is it possible?
3 Answers
You want to look into observers/observables in Java. They will allow you to do what you need.
There is a lot online about it.
Here is a little stub: http://docs.oracle.com/javase/7/docs/api/java/util/Observer.html
More here: When should we use Observer and Observable
5 Comments
If this object isn't yours and you are looking for an event listener of sorts for the property of an object, no, there are no object property listeners.
But, if you can modify the source of the object, I assume you are using getters and setters. So, you'd have something like...
public void setIntegerValue(int num){
this.num = num;
}
The most efficient thing to do is to add some sort of logic inside the setter to execute your function when the integer num is changed:
public void setIntegerValue(int num){
this.num = num;
yourFunction(); // Let your program know that num has been modified
}
1 Comment
If you use a setter method you can add calls to other methods.
First, make your property private.
private int myProp;
Then, add a setter.
public void setMyProp(int myProp) {
boolean isVariableChanged = myProp != this.myProp;
this.myProp = myProp;
// do other things
}
In this case, if the variable changed, the boolean in the method will be true, which can be used if you want to prevent triggering the method if the variable is changed back to its current value.
You will then also need a getter.
public int getMyProp() {
return myProp;
}
Generally, getters and setters are recommended to make code more maintainable when the implementation of a class changes.
However, they also give you the ability to use getters and setters as pseudo listeners.