2011-04-05 132 views
6

我試圖創建一個從該方法中返回方法名稱的函數:如何從該方法中獲取方法名稱?

public static String getMethodName(final int depth) 
    { 
    final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); 
    return ste[ste.length - 1 - depth].getMethodName(); 
    } 

然而,當我打電話從Activity.onCreate()這個方法,它返回的「主」,而不是「的onCreate」 。

如何從該方法中獲取實際的方法名稱?

回答

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

如果更改如上return語句,你會得到即時調用的方法名,五言深度shoould是零..

+0

我想你的建議的變化,現在它返回 「的getStackTrace」 。當然,我使用getMethodName(0)來調用它。 – 2011-04-05 19:10:02

+4

@Android Eve,ste [0] - > getStackTrace,ste [1] - > getMethodName,ste [2] - > getMethodName的直接調用者... – 2011-04-05 19:16:34

+0

getMethodName(2)取得了訣竅。謝謝! (和+7)。 – 2011-04-05 19:23:18

1

我認爲你的問題,也許你正在訪問堆棧倒掛。在返回的值元素中,0是最近的調用(這將是getStackTrace())。我想你正打算做的是:

public static String getMethodName(final int depth) { 
    final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); 
    return ste[1 + depth].getMethodName(); 
} 

這將訪問最新的呼叫棧(通話外的getStackTrace())。例如,如果你有一個方法:

public void foo() { 
    System.out.println(getMethodName(0)); 
} 

這將打印「foo」與上述函數的實現。當然,你也可能想添加一些邊界檢查功能,因爲它可以很容易地超出數組。

+0

我嘗試了您的建議更改,現在它返回「getStackTrace」。當然,我使用getMethodName(0)來調用它。 – 2011-04-05 19:09:43

3

儘管啓動一個異常是更昂貴的方式,但我仍然會這樣做。

Log.d("CurrentMethod", new Exception().getStackTrace()[0].getMethodName()); 

如果在onCreate中調用,則工作。

+1

我不明白 - 爲什麼創建一個異常,而不是調用'Thread.currentThread()。getStackTrace()'? – 2014-04-24 08:49:29

2

管理日誌單身:

public class ActiveLog { 
public static final String TAG = "TRACE LOG"; 
private static ActiveLog instance; 
private static boolean actif; 

public static ActiveLog getInstance() { 
    if (null == instance) 
     instance = new ActiveLog(); 
    return instance; 
} 

private ActiveLog() { 
    ActiveLog.setActif(true); 
} 

public void log() { 
    if(isActif()) 
     Log.d(TAG, "" + (new Exception().getStackTrace()[1].getClassName()) 
         + ": " 
         + (new Exception().getStackTrace()[1].getMethodName())); 
} 

public static boolean isActif() { 
    return actif; 
} 

public static void setActif(boolean actif) { 
    ActiveLog.actif = actif; 
}} 

使用的例子:

public class MyTest { 
    public void test() { 
    ActiveLog.getInstance().log(); 
    } 
} 

結果:

09-05 14:37:09.822: D/TRACE LOG(XXXX): com.TestProject.MyTest: test