获取java调用者信息

现在好多代码解耦特别严重,调用者也是特别多,以下代码获取某块代码的调用者信息,打印到控制台中。


    public static void printCaller() {
        try {
            StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace();
            String caller = "";
            String callingClass = "";
            String callFile = "";
            int lineNumber = 0;
            System.out.println("==========BEGIN OF CALLER INFO============");
            for (int i = 2; i < trace.length; i++) {
                callingClass = trace[i].getClassName();
                callingClass = callingClass.substring(callingClass
                        .lastIndexOf('.') + 1);
                caller = trace[i].getMethodName();
                callFile = trace[i].getFileName();
                lineNumber = trace[i].getLineNumber();
                String method = String.format(Locale.US, "[%03d] %s.%s(%s:%d)"
                        , Thread.currentThread().getId(), callingClass, caller, callFile, lineNumber);
                System.out.println(method);
            }
            System.out.println("==========END OF CALLER INFO============");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(获取java调用者信息)