-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
  • 794
  • 3
  • 17

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.
  • 18,900
  • 20
  • 82
  • 181
  • Ah, I see, okay thank you. – Roguebantha Aug 02 '13 at 15:03
  • 1
    @Roguebantha if this answer solves your problem consider [accepting it](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). You should also accept your own answer in your [previous question](http://stackoverflow.com/questions/14489824/using-cronjob-and-email-to-create-a-texting-server). – Pshemo Aug 02 '13 at 16:52
0
StackTraceElement[] stackElements = Thread.currentThread().getStackTrace();
System.out.println(stackElements[1].getMethodName());

You might have to check which index you want.

Sajal Dutta
  • 17,444
  • 10
  • 51
  • 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
  • 6,999
  • 9
  • 44
  • 76
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
  • 912
  • 1
  • 9
  • 16