METHOD REFERENCE

INTRODUCTION

java-logoA method reference is a feature present in Java starting with version eight, which allows us to refer to a method by its name but without directly causing it to be invoked. They are similar to lambda expressions because they use Functional interfaces for their operation, plus when used they generate an instance of a functional interface.

METHOD REFERENCE FOR STATIC METHODS

We first introduce a functional interface into our program. We introduce a class that contains two methods compatible with the functional interface, the first method by name contiene checks whether one string is contained in another via the indexOf method. The method returns a boolean that tells us whether the substring is contained(true) or not(false) in the main string. The second method checks whether two strings are equal via the equals method of the Object class.

metodi statici

Let’s look at the test class.

Test class

At the beginning of the main method we invoke the prova method which is in the same class. The method MyClass::contiene, compatible with the functional interface is a reference to a static method, is passed to the variable mi of the method prova. The contiene method of MyClass is invoked through the functional interface. The most important part of all the code are the indirect references to the static methods of MyClass, invoked through a functional interface.

METHOD REFERENCE FOR INSTANCE METHODS

We resume the previous example with the difference that this time the methods are not static but instance methods.

metodi di istanza

See the main.

main

The controlla method invoked via the variable causes mi to call the contiene and uguali methods of MyClass indirectly.

METHOD REFERENCE FOR CONSTRUCTOR

Costruttori

We introduce the functional interface that has the same parameters as the constructor and returns an object of type MyClass. Let’s look at the test class. Through an indirect constructor reference we are able to create instances of the MyClass class.

Classe di Test

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

GITHUB

EXECUTION OF THE EXAMPLE CODE

  • Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.

       java -jar –enable-preview CorsoJava.jar

  • Or run the main found in the file CorsoJava.java.