How to measure java methods?

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

For example, my Java program that I want to use 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 show something like this:

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

Thank you for your help!

+5
source share
5 answers

You can use a tool library such as a Javassist to do this.

Let me give an example for one method, you can extend it 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 more information: http://www.csg.ci.iu-tokyo.ac.jp/~chiba/javassist/tutorial/tutorial2.html#intro

+9
source

, , AspectJ ; , !: D

+4

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();
}
}

,

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

, , .

+1

, .

, , - (Hibernate/JPA - ). , . ( ).

+1

, , - , , AspectJ () Spring AOP (), , , , , , . , .

0
source

All Articles