You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在打印方法返回值的同时输出方法名称?

解决方案

因为直接传入barMethod()的调用结果只能拿到返回值,无法获取方法名,所以需要通过方法引用结合反射来实现,既保留方法的调用逻辑,又能获取方法名称。

1. 原类保持不变

public class FooClass {
    String barMethod() {
        return "baz";
    }
}

2. 实现自定义打印工具类

import java.lang.reflect.Method;
import java.util.function.Supplier;

public class PrintUtil {
    public static void customPrint(Supplier<String> methodReference) {
        try {
            // 通过反射解析方法引用,获取原方法名称
            Method getMethod = methodReference.getClass().getDeclaredMethod("get");
            String methodName = getMethod.getDeclaringClass().getEnclosingMethod().getName();
            
            // 调用方法获取返回值
            String result = methodReference.get();
            
            // 拼接输出
            System.out.println(methodName + " = " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. 调用方式

public class Main {
    public static void main(String[] args) {
        FooClass fooInstance = new FooClass();
        // 使用方法引用传入,而非直接调用方法
        PrintUtil.customPrint(fooInstance::barMethod);
    }
}

输出结果

barMethod = baz

注意事项

  • 必须使用方法引用(如fooInstance::barMethod)作为参数,不能直接传fooInstance.barMethod()(否则只会传入字符串"baz",无法获取方法名)。
  • 该方案依赖Java 8及以上的方法引用特性,反射逻辑在部分特殊场景下可能需要调整,但对于普通无参返回String的方法可以直接使用。

内容的提问来源于stack exchange,提问作者Rothin Sen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:05:23