Browse DevX
Sign up for e-mail newsletters from DevX


Tip: Know the Details of the Current Method Being Executed

See how to figure out the current code flow with the getMethodName() method.


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();

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:

[root@mypc]# java CurrentMethod
Current method(): getStackTrace
Current method(): getCurrentMethodName
Current method(): proceed
Current method(): main


Visit the DevX Tip Bank


Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date