How to instrument java methods?

前端 未结 5 665
不思量自难忘°
不思量自难忘° 2020-12-09 22:15

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

5条回答
  •  有刺的猬
    2020-12-09 22:59

    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

提交回复
热议问题