Exploring Java Method References
--
Motivation
According to Oracle’s the Java tutorials:
You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.
I am aware of method references and thought that they are what they are: a more succinct way of referring to methods without providing explicit information that the compiler already know. What I did not realize was that method references can be categorized into four different types (summary below). Among the four types, 3 of them are fairly easy to understand:
- Call to a constructor by doing
ClassName::new
instead of() -> new ClassName()
- Call to a static method by doing
ClassName::methodName
instead of() -> ClassName.methodName()
- Call to an instance method of a particular object by doing
ObjectName::methodName
instead of() -> obj.methodName()
What intrigued me was the four conditions: call to an instance method of a particular class. In that case, will JVM be creating an instance of that class and then invoking the instance method via the newly created instance?
Summary table
The hunt
After some Googling, I found a few articles about method references. So there are in fact a few ways we can do a method reference to an instance method without specifying the instance in the method reference.
Examples:
// Method references and their equivalent lambda expressions
String: : toLowerCase // (a) -> a.toLowerCase()
String: : compareToIgnoreCase // (a, b) -> a.compareToIgnoreCase(b) Integer: : compareTo // (a, b) -> a.compareTo(b)
In the above cases, it can be seen that the instance method is going to be invoked on the instance that is passed in as the first parameter. So JVM did not magically create an instance just to invoke an instance method on the specified class.