Vijay Innamuri
Vijay Innamuri

Reputation: 4372

How to print current executing method name in eclipse?

During execution of a Java program in eclipse how to print currently executing method name?

Eg:

public class Bits {
    public static void main(String[] args) {
        System.out.println("method:main");
        int result=TotSum(24,35);
        System.out.println("total sum:" + result);
    }

    private static int TotSum(int i, int j) {
        System.out.println("method:TotSum");
        return (i+j);
    }
}

Output:

method:main

method:TotSum

total sum:59

In eclipse is it possible to print the current executing method name automatically (instead of hardcoded sysout statements or logger statements in every method like the below code)?

public class Bits {
    public static void main(String[] args) {
        int result=TotSum(24,35);
        System.out.println("total sum:" + result);
    }

    private static int TotSum(int i, int j) {
        return (i+j);
    }
}

Getting the name of the current executing method

All the answers for this question suggests to add some code to the program.

But my question is to find out current executing method without adding any code.

Like an eclipse feature for Java.

Upvotes: 2

Views: 3610

Answers (1)

Willian
Willian

Reputation: 532

You might want to use a logging system like Log4J2. It has many options for configuration including printing the name of the method. Then you could use:

public class Bits {

    private static final Logger logger = LogManager.getLogger(Bits.class);

    public static void main(String[] args) {
        logger.info("Starting");
        int result=TotSum(24,35);
        logger.info("total sum:" + result);
    }

    private static int TotSum(int i, int j) {
        logger.info("method:TotSum");
        return (i+j);
    }
}

And it would print something like (depending on your pattern):

foo.bar.Bits.main Starting
foo.bar.Bits.TotSum method:TotSum
foo.bar.Bits.main total sum:59

Otherwise you may use an approach like of this answer. The following code will print the name of your method:

System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());

Or yet you may use AOP, like in this answer.

Upvotes: 6

Related Questions