Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List the names of methods being invoked

I'd like to have a reflection-like solution for displaying the methods which are called.

Example:

public class Foo {
    public void bar() {
         new Y().x();
    }
}

public class Y {
    public void x() {
    } 
} 

public class Main {
    public static void main(String[] args) {
        // SETTING UP THE MAGIC
        new Foo().bar(); 
        new Y().x();
    }
}

The output should be:

1. Foo.bar
   1.2 Y.x
2. Y.x

Optimally there could be an event handler which would be fired every time a method is called(and some info could be passed as a parameter).

PS: I don't want to use this in a production environment, I only need this for displaying output in a skeleton app without dummy copy-paste.

like image 469
David Frank Avatar asked Feb 17 '23 04:02

David Frank


2 Answers

I would use aspectj to define an aspect which writes log messages for every method call. You can find an example here: Tracing Java Method Execution with AspectJ. or here: Logging with AspectJ

The advantage of this solution is that you don't have to make any changes on your code. You will need some time to get into aspectj, but it meets your requirement very well.

like image 90
Kai Avatar answered Feb 28 '23 06:02

Kai


You would have to build a profiler agent if you wanted to achieve this without having to pollute your code.

Take a look at this article, it shows you how to do it. Specifically, look at profiling aspects lower in that article.

Listing 2 is a profiling aspect that can be used to output the class name, method name, and a timestamp every time the JVM enters or leaves a method.

like image 37
mprivat Avatar answered Feb 28 '23 04:02

mprivat