首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java使用PropertyChangeSupport和PropertyChangeListener检测变量变化

Java使用PropertyChangeSupport和PropertyChangeListener检测变量变化
EN

Stack Overflow用户
提问于 2011-01-04 05:50:17
回答 2查看 2.4K关注 0票数 0

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

代码语言:javascript
复制
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的更改:

代码语言:javascript
复制
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的值发生变化时,我都希望打印一条调试语句。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-04 05:57:29

我非常确定,只有通过PropertyEditor机制设置属性,而不是通过getter和setter,PropertyChangeListener机制才能工作

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

票数 0
EN

Stack Overflow用户

发布于 2011-01-04 06:06:29

我很抱歉这么说,但是在MysteryClass实现的情况下,如果你不能改变它的实现,你就不能改变它的实现,顺便说一句,你把PropertyChangeListener PropertyChangeSupport的概念搞错了。为了使它工作,PropertyChangeSupport MysteryClass查看Java Beans Tutorial on Bound properties,您可以做的是用您自己的类包装这个类,比如说MysteryClassWithPrint,它将实现所有公共方法作为对MysteryClass和打印消息的内部实例的委托,然后用新的MysteryClassWithPrint();替换所有的new MysteryClass();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4588683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档