Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get method name of my method's caller

Tags:

java

android

I have two methods. In one of them, I call second one. In this second one I need to know name of method, which call this (second) one.

Is this even possible?

public class Test {
  public void foo() {
    String m = getCallingMethodName();
  }
  public String getCallingMethodName() {
    return callerMethodName; //should return "foo"
  }
}
like image 288
user2126425 Avatar asked Apr 08 '15 16:04

user2126425


2 Answers

With this you can obtain the current method name:

String method_name = Thread.currentThread().getStackTrace()[1].getMethodName());
like image 83
Gio MV Avatar answered Sep 29 '22 00:09

Gio MV


The other answers here are correct, but I thought I'd add a small note of caution. This won't work if you call things using reflection and also it might not get the right stack frame if you have any AOP joinpoints / proxies etc.

For example...

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());
    }
}
like image 34
BretC Avatar answered Sep 29 '22 02:09

BretC