1

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;
    }
}
5
  • 3
    I doubt there is one. What name do you expect if someone just passes in a lambda, what name should that expression have? Commented Nov 15, 2017 at 16:09
  • There is no way, as the lambda, which you're passing is almost identical to an anonymous class implementation which just calls a method in its overriden method Commented Nov 15, 2017 at 16:14
  • I would expect that somehow the Lambda expression holds this kind information and print the method name: getInteger() Commented Nov 15, 2017 at 16:14
  • 1
    @GeorgiosStathis, well, it doesn't have this information. What if the lambda you got is something along the lines of i -> i.getMyValue().getInternal("Parameter")? What name would you expect to see? Commented Nov 15, 2017 at 16:41
  • Hmm.. I should have studied this better. I expected that since inside the samplemethod object the apply method knows to which method to use the input parameter then the method name should be retrievable somehow. Commented Nov 15, 2017 at 17:09

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.