3 回答
TA貢獻1853條經驗 獲得超6個贊
Thread.currentThread().getStackTrace()
在某些情況下,某些虛擬機可能從堆棧跟蹤中省略一個或多個堆棧幀。在極端情況下,如果虛擬機沒有有關此線程的堆棧跟蹤信息,則允許該方法返回一個零長度數組。
TA貢獻1820條經驗 獲得超9個贊
String name = new Object(){}.getClass().getEnclosingMethod().getName();YourClass$1.class.class
getEncosingMethod()java.lang.reflect.Method
getEnclosingMethod()SecurityException
getEnclosingConstructor()getEnclosingMethod()null.
TA貢獻1821條經驗 獲得超6個贊
/**
* Get the method name for a depth in call stack. <br />
* Utility function
* @param depth depth in the call stack (0 means current method, 1 means call method, ...)
* @return method name
*/public static String getMethodName(final int depth){
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
//System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
// return ste[ste.length - depth].getMethodName(); //Wrong, fails for depth = 0
return ste[ste.length - 1 - depth].getMethodName(); //Thank you Tom Tresansky}
我使用JRE 6并給出了不正確的方法名。 如果我寫 ste[2 + depth].getMethodName().
0是
getStackTrace(),
1是
getMethodName(int depth)和
2正在調用方法。
添加回答
舉報
