繁体   English   中英

Java使用PropertyChangeSupport和PropertyChangeListener检测变量更改

[英]Java Detect Variable Change Using PropertyChangeSupport and PropertyChangeListener

当某些第三方代码更改变量时,我正在尝试打印出调试语句。 例如,考虑以下内容:

public final class MysteryClass {

private int secretCounter;

public synchronized int getCounter() {
    return secretCounter;
}

public synchronized void incrementCounter() {
    secretCounter++;
}

}

public class MyClass {

public static void main(String[] args) {
    MysteryClass mysteryClass = new MysteryClass();
    // add code here to detect calls to incrementCounter and print a debug message
}

我没有能力更改第三方MysteryClass,所以我认为我可以使用PropertyChangeSupport和PropertyChangeListener来检测对secretCounter的更改:

public class MyClass implements PropertyChangeListener {

    private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this);

    public MyClass() {
        propertySupport.addPropertyChangeListener(this);
    }

    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("property changing: " + evt.getPropertyName());
    }

    public static void main(String[] args) {
        MysteryClass mysteryClass = new MysteryClass();
        // do logic which involves increment and getting the value of MysteryClass
    }
}

不幸的是,这没有用,并且我没有打印出调试消息。 有人看到我的PropertyChangeSupport和Listener接口实现有什么问题吗? 我想在每次调用incrementCounter或secretCounter的值更改时打印调试语句。

我很确定PropertyChangeListener机制仅在通过PropertyEditor机制而不是通过getter和setter设置属性时才有效

我可能会用AspectJ尝试一下,但是您只能建议方法调用,而不能建议执行,因为第三方类是最终的。

不好意思地说,但是对于MysteryClass实现,如果您不能更改它的实现,那么您将无法通过顺便将PropertyChangeListener PropertyChangeSupport概念弄错。 要使其发挥作用,PropertyChangeSupport MysteryClass参见Java Beans Tutorial的Bound属性 ,您可以做的是用您自己的类包装该类,说MysteryClassWithPrint,它将实现所有公共方法作为对MysteryClass的内部实例的委托并打印消息,然后替换所有new MysteryClass(); 带有新的MysteryClassWithPrint();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM