茫茫網海中的冷日 - 對這文章發表回應
茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1672035 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_004.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

對這文章發表回應

發表限制: 非會員 可以發表

發表者: 冷日 發表時間: 2019/4/2 6:16:27

How to Get a Name of a Method Being Executed?

Last modified: August 18, 2018

Java Top

1. Overview

Sometimes we need to know the name of the current Java method being executed.

This quick article presents a couple of simple ways of getting hold of the method name in the current execution stack.

2. Using getEnclosingMethod

We can find the name of the method being executed by using the getEnclosingMethod() API:


public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
String methodName = new Object() {}
.getClass()
.getEnclosingMethod()
.getName();
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod",
methodName);
}

3. Using
Throwable Stack Trace

Using a Throwable stack trace gives us stack trace with the method currently being executed:


public void givenThrowable_whenGetStacktrace_thenFindMethod() {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
assertEquals(
"givenThrowable_whenGetStacktrace_thenFindMethod",
stackTrace[0].getMethodName());
}

4. Using Thread Stack Trace


Also, the stack trace of a current thread (since JDK 1.5) usually includes the name of the method that is being executed:


public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
StackTraceElement[] stackTrace = Thread.currentThread()
.getStackTrace();
assertEquals(
"givenCurrentThread_whenGetStackTrace_thenFindMethod",
stackTrace[1].getMethodName());
}

However, we need to remember that this solution has one significant drawback. Some virtual machines may skip one or more stack frames. Although this is not common, we should be aware that this can happen.

5. Conclusion

In this tutorial, we have presented some examples how to get the name of the currently executed method. Examples are based on stack traces and the getEnclosingMethod().

As always, you can check out the examples provided in this article over on GitHub.


原文出處:How to Get a Name of a Method Being Executed? | Baeldung
內容圖示
url email imgsrc image code quote
樣本
bold italic underline linethrough   












 [詳情...]
validation picture

注意事項:
預覽不需輸入認證碼,僅真正發送文章時才會檢查驗證碼。
認證碼有效期10分鐘,若輸入資料超過10分鐘,請您備份內容後,重新整理本頁並貼回您的內容,再輸入驗證碼送出。

選項

Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|