简体   繁体   English

如何找出在Java中调用该方法的位置?

[英]How to find out where the method was called in Java?

I have more than 100 class files. 我有100多个班级文件。 I got an error message in one method when it return values. 返回值时,在一种方法中收到错误消息。 Example: 例:

public String name()
{
    return("John");  // error message appeared here
}

My problem is that I couldn't find out where this has been called. 我的问题是我无法找到这个位置。

You may print the calling stack this way : 您可以通过以下方式打印调用堆栈:

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste);
}

Note that most IDE have shortcuts to find where a given method is called. 请注意,大多数IDE都有快捷方式来查找调用给定方法的位置。

For instance in Eclipse, you would select your method, then Ctrl+Shift+G will show you all possible callers of the method. 例如,在Eclipse中,您将选择方法,然后Ctrl + Shift + G将向您显示该方法的所有可能调用者。

You may also use a debugger and do step-by-step check. 您也可以使用调试器并进行逐步检查。

You can try this: 您可以尝试以下方法:

StackTraceElement[] ste = Thread.currentThread().getStackTrace()

From Javadocs : Javadocs

Returns the stack trace of the thread associated with this ThreadInfo. 返回与此ThreadInfo关联的线程的堆栈跟踪。 If no stack trace was requested for this thread info, this method will return a zero-length array. 如果没有为该线程信息请求堆栈跟踪,则此方法将返回零长度的数组。 If the returned array is of non-zero length then the first element of the array represents the top of the stack, which is the most recent method invocation in the sequence. 如果返回的数组长度不为零,则数组的第一个元素表示栈顶,这是序列中最近的方法调用。 The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence. 数组的最后一个元素代表堆栈的底部,这是序列中最近的方法调用。

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

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