Java 或任何其他语言:哪个方法/类调用了我的?
我想在我的方法内部编写一个代码来打印哪个方法/类调用了它。
(我的假设是除了我的方法之外我不能改变任何东西。)
其他编程语言怎么样?
编辑:谢谢大家,JavaScript 怎么样? Python? C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是 Java 特有的。
您可以使用 Thread.currentThread()。
getStackTrace()
。这将返回StackTraceElements
。数组中的第二个元素将是调用方法。
例子:
This is specific to Java.
You can use
Thread.currentThread().
getStackTrace()
. This will return an array ofStackTraceElements
.The 2nd element in the array will be the calling method.
Example:
如果您只想打印堆栈跟踪并寻找该类,请使用
请参阅 API 文档。
If all you want to do is print out the stack trace and go hunting for the class, use
See the API doc.
贾斯汀已经掌握了一般情况;我想提一下此片段演示的两个特殊情况:
此打印:
即使第一个是从
main()
中“直接”调用的,第二个是从SomeInnerClass.someInnerMethod()
中调用的>。这是两个方法之间进行透明调用的两种情况。Justin has the general case down; I wanted to mention two special cases demonstrated by this snippit:
This prints:
Even though the first is called "directly" from
main()
and the second fromSomeInnerClass.someInnerMethod()
. These are two cases where there is a transparent call made in between the two methods.方法调用的顺序位于堆栈中。这就是获取堆栈的方式: 获取 Java 中的当前堆栈跟踪 然后获取上一项。
the sequence of method calls is located in stack. this is how you get the stack: Get current stack trace in Java then get previous item.
由于您询问了其他语言,Tcl 给您一个命令 (info level< /a>),让您检查调用堆栈。例如,
[info level -1]
返回当前过程的调用者,以及用于调用当前过程的参数。Since you asked about other languages, Tcl gives you a command (info level) that lets you examine the call stack. For example,
[info level -1]
returns the caller of the current procedure, as well as the arguments used to call the current procedure.在 Python 中,您使用 inspect 模块。
获取函数的名称和文件名很容易,如下面的示例所示。
获取函数本身需要更多工作。我认为你可以使用
__import__
函数导入调用者的模块。但是,您必须以某种方式将文件名转换为有效的模块名称。In Python you use the inspect module.
Getting the function's name and file name is easy, as you see in the example below.
Getting the function itself is more work. I think you could use the
__import__
function to import the caller's module. However you must somehow convert the filename to a valid module name.是的,这是可能的。
看一下 Thread.getStackTrace()
Yes, it is possible.
Have a look at Thread.getStackTrace()
在 Python 中,您应该使用回溯或检查模块。这些模块将使您免受解释器的实现细节的影响,这些细节即使在今天也可能有所不同(例如 IronPython、Jython),并且将来可能会发生更多变化。然而,这些模块在今天的标准 Python 解释器下执行此操作的方式是使用 sys._getframe()。特别是,sys._getframe(1).f_code.co_name 提供了您想要的信息。
In Python, you should use the traceback or inspect modules. These will modules will shield you from the implementation details of the interpreter, which can differ even today (e.g. IronPython, Jython) and may change even more in the future. The way these modules do it under the standard Python interpreter today, however, is with sys._getframe(). In particular, sys._getframe(1).f_code.co_name provides the information you want.