java 获取当前正在执行的方法的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7495249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the name of the current method being executed
提问by Norbert
Well what I am basically doing is an app which has many activities. I have a few friends with android phones and I gave them the app for testing. However, it sometimes goes into endless cycles and does strange behaviour which I am not able to understand due to their lack of programming experience and inability to dump the logcat in those particular moments.
嗯,我基本上做的是一个有很多活动的应用程序。我有几个朋友使用 android 手机,我给了他们应用程序进行测试。但是,它有时会进入无休止的循环并执行我无法理解的奇怪行为,因为他们缺乏编程经验并且无法在那些特定时刻转储 logcat。
So what I need to do is to create a static always visible window, probably popup window, that shows in which method is the program now.
所以我需要做的是创建一个静态的始终可见的窗口,可能是弹出窗口,显示现在程序在哪个方法中。
So my question would be, which is the best way to achieve this functionality and how to retrieve the current method the App is in (it has several threads).
所以我的问题是,这是实现此功能的最佳方式以及如何检索应用程序所在的当前方法(它有多个线程)。
回答by Karol Król
Thread.currentThread().getStackTrace()[1].getMethodName()
回答by Sky Kelsey
You can try this:
你可以试试这个:
public String getCurrentMethod(){
try{
throw new Exception("");
}catch(Exception e){
return e.getStackTrace()[0].toString();
}
return ""; // This never happens
}
It will return something like this:ClassName.methodName():123
它将返回如下内容:ClassName.methodName():123
回答by blessenm
There are many answers for this if you search SO. This is a simple method
如果您搜索 SO,有很多答案。这是一个简单的方法
String name = new Object(){}.getClass().getEnclosingMethod().getName();
You should refer this post. Getting the name of the current executing method
你应该参考这篇文章。 获取当前执行方法的名称
回答by golosovsky
On my device it's - Thread.currentThread().getStackTrace()[2].getMethodName()
在我的设备上 - Thread.currentThread().getStackTrace()[2].getMethodName()
(not [1] but [2])
(不是 [1] 而是 [2])