How to instrument java methods?

前端 未结 5 685
不思量自难忘°
不思量自难忘° 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:52

    In the method you could add

    public class TestInstr {
    
    public static void sayHello() {
    System.out.println("method sayHello has been called");
    System.out.println("Hello !");
    }
    
    public static void main(String args[]) {
    sayHello();
    sayHello();
    sayHello();
    }
    }
    

    You could use this to get the current method

    public String getCurrentMethodName() {
     StackTraceElement stackTraceElements[] =
             (new Throwable()).getStackTrace();
     return stackTraceElements[1].toString();
    }
    

    I'm not sure if this is what you're looking for.

提交回复
热议问题