2

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.

Community
  • 1
  • 1
Vijay Innamuri
  • 4,242
  • 7
  • 42
  • 67
  • possible duplicate of [Getting the name of the current executing method](http://stackoverflow.com/questions/442747/getting-the-name-of-the-current-executing-method) – NamshubWriter Jan 18 '15 at 04:09
  • There's nothing special about running your Java program in Eclipse, it executes just the same as outside Eclipse (and it should be, you don't want platform-dependent code) – Erwin Bolwidt Jan 18 '15 at 05:41
  • @ErwinBolwidt Yes, I don't want code to be platform dependent. So, I don't want to add any additional code to my program. But for debugging from IDE I need to trace the program. – Vijay Innamuri Jan 18 '15 at 05:49
  • @VijayInnamuri friendly reminder: it seems you forgot to mark answer as accepted – Alexander Malakhov Oct 25 '18 at 14:19

1 Answers1

6

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.

Community
  • 1
  • 1
Willian
  • 504
  • 1
  • 9
  • 22