当一些第三方代码更改变量时,我尝试打印出调试语句。例如,考虑以下内容:
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的值发生变化时,我都希望打印一条调试语句。
发布于 2011-01-04 05:57:29
我非常确定,只有通过PropertyEditor机制设置属性,而不是通过getter和setter,PropertyChangeListener机制才能工作
我可能会尝试使用AspectJ,但您只能建议方法调用,而不能建议执行,因为第三方类是最终类。
发布于 2011-01-04 06:06:29
我很抱歉这么说,但是在MysteryClass实现的情况下,如果你不能改变它的实现,你就不能改变它的实现,顺便说一句,你把PropertyChangeListener PropertyChangeSupport的概念搞错了。为了使它工作,PropertyChangeSupport MysteryClass查看Java Beans Tutorial on Bound properties,您可以做的是用您自己的类包装这个类,比如说MysteryClassWithPrint,它将实现所有公共方法作为对MysteryClass和打印消息的内部实例的委托,然后用新的MysteryClassWithPrint();替换所有的new MysteryClass();
https://stackoverflow.com/questions/4588683
复制相似问题