如何从该方法中得到的方法叫什么名字?方法、叫什么名字

2023-09-05 07:16:01 作者:一生都想和你共度

我想创建一个函数,从方法中返回方法名:

 公共静态字符串getMethodName(最终诠释深度)
  {
    最后的StackTraceElement [] STE = Thread.currentThread()的getStackTrace()。
    回报STE [ste.length  -  1  - 深度] .getMethodName();
  }
 

然而,当我打电话从Activity.onCreate()这个方法,它会返回主,而不是的onCreate。

我如何从该方法中得到实际的方法名?

解决方案

 返回STE [1 +深度] .getMethodName();
 

如果您更改return语句如上,你会得到五言深度直接调用方法名,shoould为零。

中国最热30个名字出炉 起名技巧攻略小百科 图

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?

解决方案

return ste[1+depth].getMethodName();

If you change return statement as above, you would get immediate calling method name , of cource depth shoould be zero..