如何从该方法中获取方法名称?
我正在尝试创建一个从该方法中返回方法名称的函数:
public static String getMethodName(final int depth)
{
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
return ste[ste.length - 1 - depth].getMethodName();
}
但是,当我从 Activity.onCreate() 调用此方法时,它返回“main”而不是“onCreate”。
如何从该方法中获取实际的方法名称?
I am trying to create a function that returns the method name from within that method:
public static String getMethodName(final int depth)
{
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
return ste[ste.length - 1 - depth].getMethodName();
}
However, when I call this method from Activity.onCreate(), it returns "main" instead of "onCreate".
How do I get the actual method name from within that method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您如上所述更改 return 语句,您将立即调用方法名称,当然深度应该为零。
If you change return statement as above, you would get immediate calling method name , of cource depth shoould be zero..
尽管事实上启动异常是更昂贵的方式,但无论如何我都会这样做。
如果在 onCreate 中调用则有效。
Despite the fact initiating an Exception is more expensive way, I would do it anyway.
Works if called in onCreate.
管理日志
的单例: 使用示例:
结果:
A singleton to manage logs:
An example of use:
The result:
我认为你的问题可能是你颠倒了访问堆栈。在返回值中,元素 0 是最近的调用(即 getStackTrace())。我认为您打算做的是:
这将访问堆栈中最近的调用(在调用 getStackTrace() 之外)。例如,如果您有一个方法:
这将使用上述函数的实现打印“foo”。当然,您可能还想向函数添加一些边界检查,因为它可以轻松地超出数组。
I think your problem maybe you are accessing the stack upside down. In the returned value element 0 is the most recent call (which would be getStackTrace()). I think what you are intending to do is:
This will access the most recent call in the stack (outside of the call to getStackTrace()). For example if you have a method:
This will print "foo" with the above implementation of the function. Of course you may also want to add some bounds checking to the function since it could easily go outside the array.