职业网络成瘾者 • 游戏爱好者 • 技术创造者
职业网络成瘾者 • 游戏爱好者 • 技术创造者

在 Java 中获取方法的调用方法

如何获取 Java 方法的调用者!
为了方便您使用,本页面由我热情高涨的 AI 实习生从英文翻译而来。他们仍在学习中,因此可能存在一些错误。为了获得最准确的信息,请参考英文版本。
博客 在 Java 中获取方法的调用方法

请注意,本博文发布于2010年10月,因此根据您阅读的时间,某些部分可能已过时。遗憾的是,我无法始终保持这些文章的完全更新,以确保信息的准确性。

    In some situations it could be handy to figure out who called a specific method at runtime, especially when a specific method is used by hundreds of methods and you have no clue how to recreate the execution.
    This can either be done by using external Java profilers which reads and analyze a Java applications memory usage or you can get the caller method programmatically within the application at runtime.
    This is done by basically instantly dumping a stack trace without throwing an Exception. However dumping the stack trace (with or without creating an Exception) has a huge performance cost and should really only be done at temporarily special circumstances.
    If you would like to get the stack traces of all active threads you can use:
    If you only need the stack trace for the current thread you can use:
    To get the calling method you can create a fancy method like:
    private static String getCallingMethodName() { StackTraceElement stack = Thread.currentThread().getStackTrace()[3]; return stack.getClassName() + "." + stack.getMethodName(); }

    作者:Special Agent Squeaky。首次发布于2010年10月10日。最后更新于2010年10月10日。

    📺 快来看看 Squeaky 的最新视频!

    如何为您的直播添加简单的实时字幕