Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instrument java methods?

I want to write a simple java agent which can print the name of a method called by the java program instrumented.

For example, my java program I want to instrument is:

public class TestInstr {

public static void sayHello() {
    System.out.println("Hello !");
}

public static void main(String args[]) {
    sayHello();
    sayHello();
    sayHello();
 }

}

I would like to display something like this :

method sayHello has been called
Hello !
method sayHello has been called
Hello !
method sayHello has been called
Hello !

Thanks for your help!

like image 259
kdelemme Avatar asked May 18 '12 20:05

kdelemme


1 Answers

You can use an instrumentation library such as Javassist to do that.

Let me give you an example for a single method, you can extend this to all methods using Javassist or reflection:

ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("TestInstr");
CtMethod m = cc.getDeclaredMethod("sayHello");
m.insertBefore("{ System.out.println(\"method sayHello has been called\"); }");
cc.writeFile();

Check this link for details: http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/tutorial/tutorial2.html#intro

like image 165
Hakan Serce Avatar answered Sep 21 '22 06:09

Hakan Serce