Get the method name from a java.util.function.Function

六眼飞鱼酱① 提交于 2020-01-03 04:14:06

问题


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;
    }
}

回答1:


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)

And above is again similar to the following:

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

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.



来源:https://stackoverflow.com/questions/47312142/get-the-method-name-from-a-java-util-function-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!