Method Reference in Java

If the existing method in the class already does everything that needs to be done, you can use the method reference mechanism to pass that method directly. Such a link is transmitted in the form:

  • class_name::static_method_name for a static method;
  • class_object::method_name for instance method;
  • class_name::new for the constructor.

The result is exactly the same as defining a lambda expression that calls this method.

private interface Measurable {
    public int length(String string);
}

public static void main(String[] args) {
    Measurable a = String::length;
    System.out.println(a.length("abc"));
}

Method references are potentially more efficient than using lambda expressions. They also provide the compiler with better type information, and when choosing between using a reference to an existing method or using a lambda expression, you should always prefer using a method reference.

Kinds of method references

  • to a static method;
  • on an instance method;
  • on the constructor.

Expression System.out::println

This expression illustrates the instance method reference mechanism: passing a reference to the println() method of the static out field of the System class.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed