Thursday, May 27, 2010

JavaAssist - Byte Code Enhancement simplified

JavaAssist - Byte Code Enhancement simplified.

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) {
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

Cool isn't it!!!. It can do wonders check the API section for more details.

Reference
http://www.csg.is.titech.ac.jp/~chiba/javassist/tutorial/tutorial.html#read
http://www.csg.is.titech.ac.jp/~chiba/javassist/html/


3 comments:

Yair Z said...

Very nice.
However, What bothers me is that I had to use "newInstance" and not simply new to create an object of the instrumented class.
Is there any way I can still use "new" instead?

Thanks,
Yair Z

Senthil Balakrishnan said...

Thanks for the comment. As the saying goes "Any software problem can be solved by adding another layer of indirection"

You can't avoid newInstance, it's a indirection...

buddy said...

Hi Senthil,

When you do Byte code instrumentation doesn't it make Java Byte Code JVM incompatible , I think whole idea of having Byte Code was that any program will not have access to direct memory location which is illegal in Java.

Thanks
Javin
Why String is immutable in Java