Get the current method name through current thread in Java

Description

The following code shows how to get the current method name through current thread.

Example


//w  w w  . ja v a  2s . c om
public class Main {
  public static void main(String args[]) {
    trace(Thread.currentThread().getStackTrace());

  }

  public static void trace(StackTraceElement e[]) {
    boolean doNext = false;
    for (StackTraceElement s : e) {
      if (doNext) {
        System.out.println(s.getMethodName());
        return;
      }
      doNext = s.getMethodName().equals("getStackTrace");
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy