List the names of the called methods

I would like to have a reflection-like solution for displaying the called methods.

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 Yx 2. Yx 

Optionally, there may be an event handler that will be triggered every time the method is called (and some information can be passed as a parameter).

PS: I do not want to use this in a production environment, I only need this to display the output in a skeleton application without the copy-paste dummy.

+4
source share
2 answers

I would use aspectj to define an aspect that records log messages for each method call. Here you can find an example: Tracing the execution of a Java method using AspectJ . or here: Login with AspectJ

The advantage of this solution is that you do not need to make any changes to your code. You will need some time to get into aspectj, but it fits your requirement very well.

+7
source

You will need to create an intermediary agent if you want to achieve this without polluting your code.

Take a look at the article, it will show you how to do it. In particular, look at the aspects of profiling later in this article.

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

+1
source

Source: https://habr.com/ru/post/1469243/


All Articles