简体   繁体   English

找出调用我的方法

[英]Find out which method called me

I'm tring to find out a way to get the complete method signature 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've implemented whoCallMe() method I can see that run method called it, but since I 3 overloads I can't say which one was the caller cause whoCallme return only "run" as the method name.我实现 whoCallMe() 方法的方式我可以看到调用它的 run 方法,但是由于我有 3 个重载,所以我不能说哪个是调用者,因为 whoCallme 只返回“run”作为方法名称。

Do you guys know other way where I could get the complete method signature like run(java.lang.String)?你们知道我可以获得像 run(java.lang.String) 这样的完整方法签名的其他方法吗?

You can use AspectJ to create an aspect which will apply to every method invocation and add the details about the method being invoked to a per-thread stack, and then remove it after method completes.您可以使用 AspectJ 创建一个将应用于每个方法调用的方面,并将有关被调用方法的详细信息添加到每线程堆栈,然后在方法完成后将其删除。 It's going to be insanely expensive, of course.当然,它会非常昂贵。 Most likely you don't want to do that.您很可能不想这样做。 Also you don't want to throw anything to find out who called you.此外,您不想扔任何东西来找出谁给您打电话。

Basically the answer to your question is: do not do it.基本上你的问题的答案是:不要这样做。 Explain why you think you want to do it and somebody will give you a good alternative.解释为什么你认为你想这样做,有人会给你一个很好的选择。

Also, come to think of it, you can argue that method overloading (not overriding.) is considered harmful?另外,想一想,您可以争辩说方法重载(而不是覆盖)被认为是有害的吗? Do you really need multiple different methods with different arguments and the same name?您真的需要多个具有不同 arguments 和相同名称的不同方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM