I want to know if there's any way so I could watch for variable value change when the program is running. Of course not using debugger I wanna do it Programmatically. For example:
class A
{
public static int valueToBeWatched;
}
So at runtime if in any method of any class in my project modifies this value MyValueChangeListner
event should get called.
Setting a Watch on a Variable, Field, or Other Expression To set a watch on an identifier such as a variable or field, right-click the variable or field in the Source Editor and choose New Watch. The identifier is then added to the Watches window. To create a watch for another expression: Choose Run | New Watch.
When you reassign a variable to another value, it simply changes the reference to that new value and becomes bound to it.
There is no event which is raised when a given value is changed in Javascript. What you can do is provide a set of functions that wrap the specific values and generate events when they are called to modify the values.
You cannot. There is no watch-on-modification hook built into Java itself. Obviously, you could do polling, though. But then it won't be "live".
AspectJ may allow such a think, but I'm not sure whether it holds for primitive variables, or only when you are using getters and setters.
The clean Java-way is to make the variable private
and use getters and setters.
private valueToBeWatched;
public void setValue(int newval) {
valueToBeWatched = newval;
notifyWatchers();
}
public int getValue() {
return valueToBeWatched;
}
On a side note, avoid static
whenever possible. In particular public
but not final
.
You need to replace the type int
with a class which will invoke your listener whenever the values changes. You might like to ignore setting the value when it hasn't actually changed.
e.g.
private int value;
private final MyValueChangeListener listener;
public void setValue(int value) {
if(this.value == value) return;
listener.changed(this, this.value, value);
this.value = value;
}
You can perform this replace using byte code injection, but it is much simple to change the original code.
An alternative is to monitor the value to look for changes periodically. Unless the value changes very slowly you might not see every change. You can use the Debugger API to do this but it not simple and I wouldn't suggest you use it unless you are familiar with the API already.
Java Debugger API Links
http://java.sun.com/javase/technologies/core/toolsapis/jpda/
http://docs.oracle.com/javase/6/docs/technotes/guides/jpda/
http://docs.oracle.com/javase/6/docs/jdk/api/jpda/jdi/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With