Skip to content
Advertisement

How to create change listener for variable?

Let’s say I have some variable defined using the statementint someVariable;. While the code runs, the variable’s value changes.

How can I track the changes in this variable? How could I implement some Listener that behaves like onSomeVariableChangedListener?

I also need to know when some other method in one page has been executed so I can set a Listener in another class.

Advertisement

Answer

This is one of the many reasons to hide variables behind setter/getter pairs. Then, in the setter you can notify your listener that this variable has been modified in the appropriate way. As the others have commented, there is no built in way to do exactly what you want, you need to implement it yourself.

Alternatively Benjamin brings up an interesting pattern, called the Decorator pattern, which might be useful to you if the code in question cannot be modified. You can look up more info at Wikipedia

The idea is to build a compatible wrapper around an object. Lets say your object in question is of type MyClass.

class MyClass{
    public void doFunc(){...}
}
    
class MyLoggedClass extends MyClass{
    MyClass myObject;
    
    public void doFunc(){
        //Log doFunc Call
        myObject.doFunc();
    }
}

instead of

MyClass object = new MyClass();

You would use

MyClass object = new MyLoggedClass(new MyClass());

Now your rest of the code would use object as per normal, except that each function call will be logged, or notified, etc.

As you will see in Wikipedia, this is typically done via an interface that the class in question inherits from, but this may not be possible in your case.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement