Get the method name of my calling method

I have two methods. In one of them I call the second. In this second I need to know the name of the method that calls this (second).

Is it possible?

public class Test {
  public void foo() {
    String m = getCallingMethodName();
  }
  public String getCallingMethodName() {
    return callerMethodName; //should return "foo"
  }
}
+4
source share
5 answers

With this, you can get the name of the current method:

String method_name = Thread.currentThread().getStackTrace()[1].getMethodName());
+1
source

The other answers here are correct, but I thought I would add a little note about caution. This will not work if you call things using reflection, and also cannot get the correct stack stack if you have any AOP access points / proxies, etc.

For instance...

import java.lang.reflect.Method;

public class CallerInfoFinder {

    public static void main(String[] args) throws Exception {
        otherMethod(); // Prints "main"

        Method m = CallerInfoFinder.class.getDeclaredMethod("otherMethod");

        m.invoke(null); // Prints "invoke0"
    }

    private static void otherMethod() {
        System.out.println(new Exception().getStackTrace()[1].getMethodName());
    }
}
+1
source

:

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StackTraceElement stackTraceElement = stackTraceElements[1];
String methodName = stackTraceElement.getMethodName();

Javadocs Thread#getStackTrace():

. , , , .

, , JVM.

0

getStackTrace() .

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        for (int i = 1; i < stackTraceElements.length && i<=4; i++) {
            StackTraceElement stackTraceElement = stackTraceElements[i];
            System.out.println(stackTraceElement.getClassName() + " Method "
            + stackTraceElement.getMethodName()); 

        }
0

This method shows the last 3 points of the method call hierarchy in the order they were called, ignoring the last 2 methods, which include the following method. This is very useful to catch the hierarchy of methods in a software module, where there are multiple access paths to the same location.

private static String getRecentSteps() {
    String recentSteps = "";
    StackTraceElement[] traceElements = Thread.currentThread().getStackTrace();
    final int maxStepCount = 3;
    final int skipCount = 2;

    for (int i = Math.min(maxStepCount + skipCount, traceElements.length) - 1; i >= skipCount; i--) {
        String className = traceElements[i].getClassName().substring(traceElements[i].getClassName().lastIndexOf(".") + 1);
        recentSteps += " >> " + className + "." + traceElements[i].getMethodName() + "()";
    }

    return recentSteps;
}
0
source

All Articles