-1

Say, I have some Java code

public static void method1(){
...//method body
method2();
}
public static void method2(){
...//method body
}

I want method2 to be able to know, as a String, what method called it. For example, in this case, if method1 were run, calling method2, method2 could print out that it was called from method1.

Thanks in advance!

Roguebantha
  • 814
  • 4
  • 19

4 Answers4

4
StackTraceElement[] ste = Thread.currentThread().getStackTrace();

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

D.R.
  • 20,268
  • 21
  • 102
  • 205
0
StackTraceElement[] stackElements = Thread.currentThread().getStackTrace();
System.out.println(stackElements[1].getMethodName());

You might have to check which index you want.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
0

I think you need something like that:

public class App
{   
    static public void main(String[] args) {
        secondMethod();
    }   

    public static void secondMethod() {
        StackTraceElement[] ste = Thread.currentThread().getStackTrace();
        System.out.println(ste[ste.length-1]);          
    }
}
user1883212
  • 7,539
  • 11
  • 46
  • 82
0

Try this

public class TestClass {
    public static void main(String... args) {
        m1();
    }

    static void m1() {
        m2();
    }

    static void m2() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        System.out.println(stackTrace[2].getMethodName());
    }
}
Mangoose
  • 922
  • 1
  • 9
  • 17