Find out which method called me

I am trying to find a way to get the complete signature of a method that is calling me.

For example:

public class Called {

    public void whoCallMe() {
        System.out.println("Caller Method: " + new Throwable().getStackTrace()[1].getMethodName());
    }
}

public class Caller {

public static void run(int i) {
    new Called().whoCallMe();
}

public static void run(String str) {
    new Called().whoCallMe();
}

public static void run(boolean b) {
    new Called().whoCallMe();
}

/** MAIN **/
public static void main(String[] args) {
    run("hi");
}

      

The way I implemented the whoCallMe () method, I can see that the run method called it, but since I have 3 overloads, I can't tell which one was the caller because whoCallme only returns "run" as the method name.

Do you guys know another way that I can get the full signature of a method like run (java.lang.String)?

+3


source to share


1 answer


You can use AspectJ to create an aspect that will apply to each method call and add information about the method being called to the thread's stack and then remove it after the method completes. Of course it will be insanely expensive. Chances are you don't want to do this. Also, you don't want to throw anything to find out who called you.

Basically the answer to your question is: don't do this. Explain why you think you want to do this and someone will give you a good alternative.



Also, think about it, you could argue that method overloading (not overriding!) Is considered harmful. Do you really need several different methods with different arguments and with the same name?

+1


source







All Articles