Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java使用PropertyChangeSupport和PropertyChangeListener检测变量更改_Java_Propertychangesupport - Fatal编程技术网

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

Java使用PropertyChangeSupport和PropertyChangeListener检测变量更改,java,propertychangesupport,Java,Propertychangesupport,我试图在第三方代码更改变量时打印调试语句。例如,考虑以下内容: public final class MysteryClass { private int secretCounter; public synchronized int getCounter() { return secretCounter; } public synchronized void incrementCounter() { secretCounter++; } } public class M

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

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
mechanis而不是通过getter和setter设置属性时才有效


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

我很抱歉这么说,但是在MysteryClass实现的情况下,如果您不能更改它的实现,那么您就不能更改它的实现。顺便说一句,您的PropertyChangeListener PropertyChangeSupport概念完全错误。要使其正常工作,请参阅 您可以使用自己的类包装该类,比如MysteryClassWithPrint,它将实现所有公共方法,作为对MysteryClass内部实例的委托,并打印消息
然后替换所有
newmysteryclass()带有新的
MysteryClassWithPrint()

您知道在通过setter更改属性时获取调试语句的另一种方法吗?Eclipse的调试器可以在变量更改时停止,我希望能做类似的事情。