从java.util.function.Function获取方法名称 [英] Get the method name from a java.util.function.Function

查看:610
本文介绍了从java.util.function.Function获取方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取java.util.function.Function的方法名称。我想每次都记录正在使用的方法的名称。以下示例打印Lambda对象,但我没有找到一种简单的方法来获取方法名称:

Is it possible to get the method name of a java.util.function.Function. I would like to log each time the name of the method being used. The following example prints the Lambda object but I have not found an easy way to get the method name:

public class Example {

    public static void main(String[]  args) {
        Example ex = new Example();
        ex.callService(Integer::getInteger, "123");
    }

    private Integer callService(Function<String, Integer> sampleMethod, String input) {
            Integer output = sampleMethod.apply(input);
            System.out.println("Calling method "+ sampleMethod);
            return output;
    }
}


推荐答案

你在传递方法引用时,必须考虑一下你实际在做什么。因为:

You have to think about, what you're actually doing, when passing a method reference. Because this:

Integer::getInteger

这几乎是相同的(对于下面的方法有更多的堆栈层):

Is almost identical (there is a stack layer more with the below approach) to this:

s -> Integer.getInteger(s)

以上类似于以下内容:

new Function<String, Integer> {
    @Override
    public Integer apply(String s){
        return Integer.getInteger(s);
    }
}

在最后一个片段中你清楚地看到有没有与被调用方法的逻辑连接 Integer#getInteger(String)。这解释了为什么在不引入新内容的情况下不可能做到你想做的事情。

And in the last snippet you clearly see that there is no logical connection to the called method Integer#getInteger(String). Which explaind why it is impossible to do what you intend without introducing something new.

这篇关于从java.util.function.Function获取方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆