dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Know the Details of the Current Method Being Executed

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


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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:

[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.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Thanks for your registration, follow us on our social networks to keep up-to-date