首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 獲取當前執行位置:文件名、類名、方法名、行號

     編輯:Java 相關知識

核心 API

Throwable.getStackTrace() 返回 StackTraceElement[],索引 0 為當前方法,1 為調用者。

工具類

public class StackTraceUtil {
    private static StackTraceElement caller() {
        return new Throwable().getStackTrace()[1];
    }

    public static int getLineNumber() { return caller().getLineNumber(); }
    public static String getMethodName() { return caller().getMethodName(); }
    public static String getFileName() { return caller().getFileName(); }
    public static String getClassName() { return caller().getClassName(); }

    // 組合信息
    public static String getLocation() {
        StackTraceElement e = caller();
        return e.getFileName() + ":" + e.getLineNumber() + " " + e.getClassName() + "." + e.getMethodName();
    }
}

使用示例

public class Demo {
    public static void main(String[] args) {
        foo();
    }
    static void foo() { bar(); }
    static void bar() {
        System.out.println(StackTraceUtil.getLocation());
        // 輸出: Demo.java:10 Demo.bar
    }
}

應用場景

  • 日誌框架自動記錄調用位置 (Log4j/Slf4j 底層即此原理)。
  • 調試工具、性能剖析、異常上下文增強。
  • 動態代理、AOP 獲取目標方法信息。

性能提示

創建 Throwable 並獲取堆棧較重,高頻調用建議緩存或使用 Java 9 StackWalker (支持懶加載、過濾)。

StackWalker 現代寫法

public static String getLocationModern() {
    return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
        .walk(s -> s.skip(1).findFirst()
            .map(f -> f.getFileName() + ":" + f.getLineNumber() + " " + f.getClassName() + "." + f.getMethodName())
            .orElse("unknown"));
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved