Function<String, Integer> f = Integer::new;
Integer i = f.apply("100");
How this turns to use Integer.parseInt when we are calling f.apply?
Function<String, Integer> f = Integer::new;
Integer i = f.apply("100");
How this turns to use Integer.parseInt when we are calling f.apply?
I surmise that your question is: "How does javac know to invoke parseInt here"?
Your snippet is broken; the generics fell off. As is, your code won't compile, as the reference is ambiguous. If you add it back in, it will compile and works as normal:
Function<String, Integer> f = Integer::new;
Integer i = f.apply("100");
Forget the new :: syntax or the Function part; they are red herrings.
So let's make it simpler:
Integer i = new Integer("100");
That is valid java; i will end up holding the value 100.
It works because... that constructor exists. It is specced to act precisely as Integer.parseInt with a radix of 10 works, and it is deprecated, for 2 good reasons: [A] invoking new Integer() at all, with any value, is deprecated (use Integer.valueOf), and [B] just call parseInt.
First off, that's not a method reference, it's a lambda.
What you might mean to do is Function<String, Integer> f = Integer::parseInt.
The Java compiler turns that lambda expression into a Function object where the apply method is overriden by what's in the lambda. Lambda expressions are basically syntactic sugar that you use to create instances of interfaces that only have one method (they're called functional interfaces). For all intents and purposes that lambda gets expanded to:
class FunctionImpl extends Function<String, Integer> {
@Override
public Integer apply(String s) {
return new Integer(s); //which calls Integer.parseInt(s) internally
}
}
Function f = new FunctionImpl();
However, in the actual bytecode, there's a new method generated and a special opcode called invokevirtual that calls that method.
apply comes from Java 8's Function class.
R apply(T t)
Applies this function to the given argument.
Parameters: t - the function argument Returns: the function result