Flat Preloader Icon

Java Method References

In Java, method references provide a way to refer to methods without invoking them. They act as a shorthand notation for a lambda expression that calls just a single method. Method references can be used to point to static methods, instance methods, and constructors, depending on the context.

Java Supports Four Types Of Method References

Reference to a static method:

  • This references a static method using the class name. The syntax is ClassName::staticMethodName.

Reference to an instance method of a particular object:

  • This references an instance method of a particular object. The syntax is objectReference::instanceMethodName.

Reference to an instance method of an arbitrary object of a particular type:

  • This references an instance method of an arbitrary object of a particular type. The syntax is ClassName::instanceMethodName.

Reference to a constructor:

  • This references a constructor. The syntax is ClassName::new.

Here’s an example that demonstrates different types of method references:

				
					import java.util.Arrays;
import java.util.List;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Reference to a static method
        List<String> names = Arrays.asList
        ("John", "Doe", "Jane", "Smith");
        names.forEach(System.out::println);

        // Reference to an instance method 
        of a particular object
        String prefix = "Hello, ";
        names.forEach(prefix::concat);

        // Reference to an instance method 
        of an arbitrary object of a particular type
        names.forEach(String::toUpperCase);

        // Reference to a constructor
        List<Integer> numbers = Arrays.asList
        (1, 2, 3, 4, 5);
        numbers.stream().map(String::valueOf)
        .forEach(System.out::println);
    }
}

				
			
  • In this example, we have used method references in the context of the forEach method and the map method of the Stream interface. Each method reference used corresponds to one of the types mentioned earlier.

Method references are particularly useful when the behavior of the lambda expression is solely to call a specific method. They help in making the code more readable and succinct by avoiding the need to define a lambda expression explicitly.

Reference To A Constructor

  • You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface.
				
					interface Messageable{  
    Message getMessage(String msg);  
}  
class Message{  
    Message(String msg){  
        System.out.print(msg);  
    }  
}  
public class ConstructorReference {  
    public static void main(String[] args) {  
        Messageable hello = Message::new;  
        hello.getMessage("javaprogramer");  
    }  
}  
				
			

Output:

				
					javaprogramer