如何观察变量的变化 [英] How to watch a variable for changes

查看:33
本文介绍了如何观察变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以在程序运行时观察变量值的变化.当然不使用调试器,我想以编程方式.例如:

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;
}

所以在运行时,如果在我的项目中任何类的任何方法中修改了这个值,MyValueChangeListner 事件应该被调用.

So at runtime if in any method of any class in my project modifies this value MyValueChangeListner event should get called.

推荐答案

您需要将 int 类型替换为一个类,该类将在值更改时调用您的侦听器.当值实际上没有改变时,您可能希望忽略它的设置.

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.

例如

 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.

另一种方法是监视值以定期查找更改.除非值变化非常缓慢,否则您可能看不到每一个变化.您可以使用 Debugger API 来执行此操作,但这并不简单,除非您已经熟悉该 API,否则我不建议您使用它.

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 调试器 API 链接

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/

这篇关于如何观察变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆