当某些第三方代码更改变量时,我正在尝试打印调试语句。例如,考虑以下情况:
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
}
我没有能力更改第 3 方 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 的值发生变化时,我都想打印一条调试语句。