java 中獲得當前方法名及行號.....---可以做日誌記錄及跟蹤

來源:互聯網
上載者:User

jdk1.5以前:

 

(new Exception()).getStackTrace()[2].getMethodName()

(new Exception()).getStackTrace()[2].getClassName()()

(new Exception()).getStackTrace()[2].getLineNumber()

 

jdk1.5之後

 

Thread.currentThread() .getStackTrace()[2].getMethodName()

Thread.currentThread() .getStackTrace()[2].getClassName()()

Thread.currentThread() .getStackTrace()[2].getLineNumber()

其實看看原始碼

 

Thread.currentThread() .getStackTrace()中就是用的 (new Exception()).getStackTrace()

如下:

/** * Returns an array of stack trace elements representing the stack dump * of this thread. This method will return a zero-length array if * this thread has not started or has terminated. * If the returned array is of non-zero length then the first element of * the array represents the top of the stack, which is the most recent * method invocation in the sequence. The last element of the array * represents the bottom of the stack, which is the least recent method * invocation in the sequence. * * <p>If there is a security manager, and this thread is not * the current thread, then the security manager's * <tt>checkPermission</tt> method is called with a * <tt>RuntimePermission("getStackTrace")</tt> permission * to see if it's ok to get the stack trace. * * <p>Some virtual machines may, under some circumstances, omit one * or more stack frames from the stack trace. In the extreme case, * a virtual machine that has no stack trace information concerning * this thread is permitted to return a zero-length array from this * method. * * @return an array of <tt>StackTraceElement</tt>, * each represents one stack frame. * * @throws SecurityException * if a security manager exists and its * <tt>checkPermission</tt> method doesn't allow * getting the stack trace of thread. * @see SecurityManager#checkPermission * @see RuntimePermission * @see Throwable#getStackTrace * * @since 1.5 */ public StackTraceElement[] getStackTrace() { if (this != Thread.currentThread()) { // check for getStackTrace permission SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission( SecurityConstants.GET_STACK_TRACE_PERMISSION); } if (!isAlive()) { return EMPTY_STACK_TRACE; } return dumpThreads(new Thread[] {this})[0]; } else { // Don't need JVM help for current thread return (new Exception()).getStackTrace(); } }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.