2011-01-03 3 views
0

제 3 자 코드가 변수를 변경하면 디버그 문을 인쇄하려고합니다. 예를 들어, 다음 사항을 고려PropertyChangeSupport 및 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 
} 

나는 제 3 자 MysteryClass을 변경하는 기능이없는, 그래서 내가 secretCounter 변경 감지에 의해 PropertyChangeSupport 및 PropertyChangeListener를 사용할 수 있다고 생각 :

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 값이 변경 될 때마다 디버그 문을 인쇄하려고합니다.

답변

0

나는 당신이 PropertyEditor 메커니즘 정보를 통해 속성을 설정하면 PropertyChangeListener 메커니즘뿐만 아니라 getter 및 setter

아마 AspectJ를 함께 그것을 시도 싶지만, 당신은 단지 메소드 호출을 조언 해 줄 수 있습니다 통해 작동 확신 해요 실행이 아니라 제 3 자 클래스가 최종입니다.

+0

속성이 설정자를 통해 변경 될 때 디버그 문을 얻는 다른 방법을 알고 있습니까? 이클립스의 디버거는 onChange 변수를 멈출 수 있고 비슷한 것을하기를 희망했다. – Sam

+0

@ 샘 내 업데이트를 참조하십시오 –

0

미안하지만, MysteryClass 구현의 경우, 구현을 변경할 수 없다면 PropertyChangeListener PropertyChangeSupport 개념을 완전히 잘못 이해할 수 없으며, 그렇게 할 수도 없습니다. 그것을 만들 수 있습니다 PropertyChangeSupport MysteryClass Java Beans Tutorial on Bound properties 당신이 할 수있는 일은 자신의 클래스로 클래스를 래핑하는 것입니다 MysteryClass의 내부 인스턴스에 대한 위임으로 모든 공용 메소드를 구현하고 메시지를 인쇄 할 수있는 말을 할 수 있습니다. 그리고 모두 new MysteryClass(); 새로운 기능 MysteryClassWithPrint();

+0

고마워하지만 링크가 작동하지 않았다 .... – Luca

+0

고마워! 고정 :-) –