Know the Details of the Current Method Being Executed

You might be interested to know where the current code flow is. The getMethodName() method in the getStackTrace(), if used as illustrated below, is really helpful.

As always, specific use cases to be defined and the available features to be used accordingly.

Code snippet:

public class CurrentMethod{public static void main(String args[]){CurrentMethod currentMethod = new CurrentMethod();currentMethod.proceed();}private void proceed(){System.out.println( "Current method(): " + getCurrentMethodName(0)); System.out.println( "Current method(): " + getCurrentMethodName(1)); System.out.println( "Current method(): " + getCurrentMethodName(2)); System.out.println( "Current method(): " + getCurrentMethodName(3)); //The index needs to be provided carefully, else it results in ArrayIndexOutOfBoundsException}String getCurrentMethodName(int index) {return Thread.currentThread().getStackTrace()[index].getMethodName(); }}/*

Expected output:

[[email protected]]# java CurrentMethodCurrent method(): getStackTraceCurrent method(): getCurrentMethodNameCurrent method(): proceedCurrent method(): main*/
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: