サードパーティのコードが変数を変更したときに、デバッグ ステートメントを出力しようとしています。たとえば、次のことを考慮してください。
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 の値が変更されるたびに、デバッグ ステートメントを出力したいと考えています。