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

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

问题描述

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

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.

另一种方法是监控值以定期查找更改。除非值变化非常缓慢,否则您可能看不到每一个变化。您可以使用调试器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天全站免登陆