Get Current Execution Method Name Inside a Method in Java - Java @ Desk

Thursday, April 3, 2014

Get Current Execution Method Name Inside a Method in Java

Get Current Execution Method Name Inside a Method in Java

Current method name that is getting executed is required many a times for logging purpose. We can any way hard code the method name in logger, but its a good practice to use any of the below mentioned strategy so that even if the method name is changed by any programmer in future, no need to change the log.

We can get the method name of the currently executing method inside the method using following classes :
1) Object - Using the getEnclosingMethod() method
2) Throwable - Using the StackTraceElement class. Need to get the method name at 0th position in the array
3) Thread - Using the StackTraceElement class. Need to get the method name at 1st position in the array

Client Code

public class GetMethodName {

 public static void main(String args[]) {
  getMethodNameUsingObject();
  getMethodNameUsingThrowable();
  getMethodNameUsingThread();
 }

 public static void getMethodNameUsingObject() {
  String methodNameUsingObject = new Object() {
  }.getClass().getEnclosingMethod().getName();
  System.out
    .println("Get Currently Method Execution Name Using Object Class - "
      + methodNameUsingObject);
 }

 public static void getMethodNameUsingThrowable() {
  StackTraceElement stackTraceElements[] = (new Throwable())
    .getStackTrace();
  System.out
    .println("Get Currently Method Execution Name From Stack Trace - "
      + stackTraceElements[0].getMethodName());
 }

 public static void getMethodNameUsingThread() {
  System.out
    .println("Get Currently Method Execution Name From Thread - "
      + Thread.currentThread().getStackTrace()[1]
        .getMethodName());
 }
}






1 comment:

  1. Thanks for posting this. This is a very nice and simple to understand post on Java GetMethodName .

    ReplyDelete