Display the current method name in Java

Java 8Object Oriented ProgrammingProgramming

The current method name that contains the execution point that is represented by the current stack trace element is provided by the java.lang.StackTraceElement.getMethodName() method.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Demo {
   public static void main(String args[]) {
      System.out.println
      ("The method name is: " + new Exception().getStackTrace()[0].getMethodName());
   }
}

Output

The method name is: main

Now let us understand the above program.

The method getMethodName() is used to obtain the current method name that contains the execution point that is represented by the current stack trace element. This is printed using System.out.println(). A code snippet which demonstrates this is as follows −

System.out.println
("The method name is: " + new Exception().getStackTrace()[0].getMethodName());
raja
Published on 09-Jan-2019 16:29:22
Advertisements