Hi,
I am just wondering if it is possible to have the following work (i.e. print out: 20 10) without having to use the javassist classloader?
class Observed {
public int n;
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
}
class Observer {
public static void writeX(Object target, int value) {
System.out.println(value);
}
}
public class ObsObrTest {
public static void main(String[] args) throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass theObserved = cp.get("Observed");
CtClass theObserver = cp.get("Observer");
CodeConverter conv = new CodeConverter();
conv.replaceFieldWrite(theObserved.getField("n"), theObserver, "writeX");
theObserved.instrument(conv);
Class c = theObserved.toClass();
Observed instanceOfObserved = (Observed)c.newInstance();
instanceOfObserved.n = 20; //should cause the output of 20
instanceOfObserved.setN(10); //should cause the output of 10
}
}