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

Google 自訂搜尋

Goole 廣告

隨機相片
HoneyMoon_Day3_00098.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

爪哇咖啡屋 : [轉貼]getting only name of the class Class.getName()

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15773
[轉貼]How to Get a Name of a Method Being Executed?

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
前一個主題 | 下一個主題 | | | |

討論串




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