函数调用方信息

本文介绍了如何在Java中获取函数调用者的类名和方法名。通过创建并分析`Throwable`实例的堆栈轨迹,可以获取到调用栈上的信息。示例代码展示了如何实现`printCallerInfo`函数,该函数打印出调用它的方法的详细信息。这种方法也被用在日志框架中来推断调用者的上下文。
摘要由CSDN通过智能技术生成

LIXIFUN - 函数调用方信息

日志框架打印的信息,前面出现的类名,方法名,在配置文件里可以进行配置,那它是从哪里拿到的信息呢?

抽出来一个题目,实现一个函数,打印调用方的信息,类名,方法名等。

例如:

public class Caller {

    public static void main(String[] args) {
        printCallerInfo();
    }

    private static void printCallerInfo() {
        // TODO
        // 打印结果应该是 main
    }
}

这些信息在 Java 这种运行时保留调用栈的语言中,只要直接从 StackTrace 里往外拿信息就可以了,具体如下:

public class Caller {

    public static void main(String[] args) {
        printCallerInfo();
    }

    private static void printCallerInfo() {
        Throwable t = new Throwable();
        StackTraceElement caller = t.getStackTrace()[1];
        System.out.println(caller.getClassName() + "#" + caller.getMethodName());
    }
}

查看 JDK 的 java.util.logging.LogRecord#inferCaller 方法,可以看到实现就是这样的。

// Private method to infer the caller's class and method names
    private void inferCaller() {
        needToInferCaller = false;
        JavaLangAccess access = SharedSecrets.getJavaLangAccess();

        // 主要就是下面的,通过 throwable 拿到 StackTrace 信息
        Throwable throwable = new Throwable();
        int depth = access.getStackTraceDepth(throwable);

        boolean lookingForLogger = true;
        for (int ix = 0; ix < depth; ix++) {
            // Calling getStackTraceElement directly prevents the VM
            // from paying the cost of building the entire stack frame.
            StackTraceElement frame =
                access.getStackTraceElement(throwable, ix);
            String cname = frame.getClassName();
            boolean isLoggerImpl = isLoggerImplFrame(cname);
            if (lookingForLogger) {
                // Skip all frames until we have found the first logger frame.
                if (isLoggerImpl) {
                    lookingForLogger = false;
                }
            } else {
                if (!isLoggerImpl) {
                    // skip reflection call
                    if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) {
                       // We've found the relevant frame.
                       setSourceClassName(cname);
                       setSourceMethodName(frame.getMethodName());
                       return;
                    }
                }
            }
        }
        // We haven't found a suitable frame, so just punt.  This is
        // OK as we are only committed to making a "best effort" here.
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lixifun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值