JavaAssist is a class library to manipulate your Java Byte Code without touching the source. Let's take an example of measuring
time taken to execute a method.
public class Subject {
    /**
     * Timetaken for start & end of the method
     * 
     * @throws InterruptedException
     */
    public void method2() throws InterruptedException {
        // Some business logic :)
        Thread.sleep(2000);
    }
}
To measure time taken for executing subject.method2(), you could enhance the Subject.methods() by adding code start and end of the method as shown.
public class JavaAssist {
    public static void main(String[] args) {
        timeTaken();
    }
    public static void timeTaken() {
        try {
            ClassPool p = ClassPool.getDefault();
            CtClass cc = p.get("Subject");
            CtMethod meth2 = cc.getDeclaredMethod("method2");
            meth2.insertBefore("System.out.println(\" Start : \"+new java.util.Date());");
            meth2.insertAfter("System.out.println(\" End : \"+new java.util.Date());");
            // cc.writeFile(".");
            Class c = cc.toClass();
            Subject s = (Subject) c.newInstance();
            s.method2();
            cc.detach();
        } catch (Exception e) {
            // suppressed
        }
    }
}
Output:
Start : Wed May 26 17:24:18 EDT 2010
End : Wed May 26 17:24:20 EDT 2010
Reference
http://www.csg.is.titech.ac.jp/~chiba/javassist/tutorial/tutorial.html#read
http://www.csg.is.titech.ac.jp/~chiba/javassist/html/
Origin Post from:
http://www.senthilb.com/2010/05/javaassist-byte-code-enhancement.html