ADHREQQGA7TT
Program to demonstrate how to get name of current executed method and list of methods executing on the stack of main Thread in Java.
ADHREQQGA7TT
Program to demonstrate how to get name of current executed method and list of methods executing on the stack of main Thread in Java.
package com.hubberspot.example; public class CurrentExecutedMethodName { public static void main(String[] args) { System.out.println("In method : main()"); // Getting the Current Thread executing main method Thread thread = Thread.currentThread(); // Getting an array of elements on stack trace of thread StackTraceElement[] stackTraceElements = thread.getStackTrace(); // Using the getMethodName() of StackTraceElement // We obtain the executing method on the stack System.out.println("Method name is : "+ stackTraceElements[1].getMethodName()); // Adding yet another method on the stack methodA(); } private static void methodA() { System.out.println("In method : methodA()"); Thread thread = Thread.currentThread(); StackTraceElement[] stackTraceElements = thread.getStackTrace(); System.out.println("Method name is : "+ stackTraceElements[1].getMethodName()); // Adding yet another method on the stack methodB(); } private static void methodB() { System.out.println("In method : methodB()"); Thread thread = Thread.currentThread(); StackTraceElement[] stackTraceElements = thread.getStackTrace(); System.out.println("Method name is : "+ stackTraceElements[1].getMethodName()); // Adding yet another method on the stack methodC(); } private static void methodC() { System.out.println("In method : methodC()"); Thread thread = Thread.currentThread(); StackTraceElement[] stackTraceElements = thread.getStackTrace(); System.out.println("Method name is : "+ stackTraceElements[1].getMethodName()); // Adding yet another method on the stack // This method will print list of all methods // on the stack trace waiting for the execution completeStackTrace(); } private static void completeStackTrace() { System.out.println("In method : completeStackTrace()"); Thread thread = Thread.currentThread(); StackTraceElement[] stackTraceElements = thread.getStackTrace(); System.out.println(); System.out.println("Printing Complete Stack Trace ... \n"); // Looping the StackTraceElements and printing // the methods of it for(int i = 0; i< stackTraceElements.length; i++) { System.out.println("Method at "+ i +" : "+ stackTraceElements[i].getMethodName()); } } }Output of the program :
ADHREQQGA7TT