Exploring Java Method References

LIU YONGLIANG
4 min readMar 14, 2021

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

--

--

LIU YONGLIANG

Computer Science Student @ National University of Singapore. Connect with me @ https://www.linkedin.com/in/-yong-/