[jboss-user] [Javassist user questions] - Simple Field Interseption

roja do-not-reply at jboss.com
Thu Sep 6 20:40:04 EDT 2007


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
  |         
  |     }
  | }
  | 

Cheers
Roja

View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4081913#4081913

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4081913



More information about the jboss-user mailing list