Method reference java 8

In java we refer classes using variables. We call methods using the reference variable of class. Wouldn't it be great if we can refer the methods also? Thanks to java 8 feature releases, we can do it. Method reference in java 8 allows us to refer methods with class and method name directly.

Before going further, you should know about lambda expressions. Using lambda we can create anonymous functions for class without creating object or implementing. This helps to pass small functions as arguments.

Method reference is shorter way of writing lambdas expressions. Sometimes we just have another method call in a method body in such case method reference is used.

Where we can use java method reference

Using simple Java

public void printString(String str){

System.out.println(str);

}

for(User user : userList){

userService.update(user);

}

similarly using lambda

(s) -> System.out.println(s);
users.stream().forEach( user-> userService.update(user);)

These are the cases when we can use java 8 method reference so that code will be clean and easy to read.

Syntax of java 8 method reference

CLass :: mehtodName

Object ::methodNam

Most noteworthy point to notice is that in method reference syntax we use  " :: "  operator not the  " . "  operator. We don’t need to pass arguments. Arguments are provided by the context variables.

The most important point to note is we can only use method reference for lambda expression having single line of another method call.

Different ways of method references in java

Reference TypeLambda ExpressionMethod Reference
Static Method Reference(args) -> Class.staticMethod(args)
eg: (String s) -> Long.parseLong(s)
Class::staticMethod
eg: Long::parseLong
Object Method Reference(args) -> obj.instanceMethod(args)
eg: (s) -> System.out.println(s)
obj::instanceMethod
eg: System.out::println
Instance Method Reference By Class Type(obj, args) -> obj.instanceMethod(args)
eg: (str) -> str.length()
Class::instanceMethod
eg: String::length
Constructor Reference(args) -> new Class(args)
eg: (size)->new ArrayList(size)
Class::new
eg: ArrayList::new

Static method reference in java

As we know in java we can call static methods using class name without creating object. Similarly, we can refer static methods using class name.

StaticClass :: staticMethod

Example of java static method reference

In the example we have MethodReferenceTest class and static method print. Print method can have any logic. We are just printing message on console.

In main method we have created an Optional variable. Then call print method for the variable using class name.

public class MethodReferenceTest {

public static void print(String msg) {

// ….. some logic

System.out.println("Printing: "+msg)

// ….. some logic

}

public static void main(String[] args) {

Optional<String> msg = Optional.of("StackTraceGuru");

//Using Lambda expression

msg.ifPresent(text->MethodReferenceTest.print(text));

//Using Method reference to print method from MethodReferenceTest class

msg.ifPresent(MethodReferenceTest::print);

}

}


Output :
Printing: StackTraceGuru
Printing: StackTraceGuru

In the example we have called print method using lambda expression and equivalent Static method reference format.

Object method reference in java

In java if we need objects to call methods. However if in lambda expression we just have method call using object, We can refer such methods using class objects.
classObject :: methodName

Example of object method reference in java

We will use same example as static method reference, with the small change. First of all we have removed static from print method so it is a normal method now.

public class MethodReferenceTest {

public static void print(String msg) {

System.out.println("Printing: "+msg)

}

public static void main(String[] args) {

Optional<String> msg = Optional.of("StackTraceGuru");

MethodReferenceTest obj =new MethodReferenceTest();

//Using Lambda expression

msg.ifPresent(text-> obj.print(text));

//Using Method reference to print method from MethodReferenceTest class

msg.ifPresent(obj::print);

}

}


Output :
Printing: StackTraceGuru
Printing: StackTraceGuru

In the example we have called print method using lambda expression and equivalent Object method reference format.

Object method reference By class type in java

Method reference can be used, if we have method calling from object while object is provided by context.

In the other words we can say the lambda expression scenario where we are just calling method and object is a input as from argument. Then we can use Method reference using class type. In this case the class type of object is used to called method.

ClassName :: methodName

Example of method reference by class type in java

In the example we have person class. Person class is having method printDetails. In another class we have main method. We have created an Optional variable of person type. We have to call printDetails method for the object.

class Person{

private String name;

public Person(String name) {

this.name = name;

}

public void printDetials(){

System.out.println("Person name is : "+name);

}

}
public class MethodReferenceTest {

public static void main(String[] args) {

Optional<Person> person = Optional.of(new Person("Mac"));

//Using Lambda expression

person.ifPresent(obj -> obj.printDetials());

//Using Method reference to print method from MethodReferenceTest class

person.ifPresent(Person::printDetials);

}

}


Output :
Person name is : Mac
Person name is : Mac

In the example we have called printDetails method  on the person object. The method is not static. It is not invoked using the class name.

Reference to constructor in java

If we are just creating new object in lambda expression, we can use constructor reference.

ClassName :: new

Example of constructor method reference in java

Similarly as previous example we have person class. Person class need a parameter to create new object. In main method we have Optional variable of String. We have to create person object from the name.

class Person{

private String name;

public Person(String name) {

this.name = name;

}

public void printDetials(){

System.out.println("Person name is : "+name);

}

}

public class MethodReferenceTest {

public static void main(String[] args) {

Optional<String> msg = Optional.of("Mac");

//Using Lambda expression

msg.map (str-> new Person(o)).ifPresent(obj -> obj.printDetials());

//Using Method reference to print method from MethodReferenceTest class

msg.map(Person::new).ifPresent(Person::printDetials);

}

}


Output :
Person name is : Mac
Person name is : Mac

In the example we have created person object using parameterized constructor. After that we have called printDetails method from the created object.

Fast track reading :

  • Method reference in java allows us to refer methods with class and method name directly.
  • Used to replace lambdas expressions having only another method call
  • Syntax CLass :: mehtodName OR Object ::methodName
Reference TypeLambda ExpressionMethod Reference
Static Method Reference(args) -> Class.staticMethod(args)Class::staticMethod
Object Method Reference(args) -> obj.instanceMethod(args))obj::instanceMethod
Instance Method Reference By Class Type(obj, args) -> obj.instanceMethod(args)Class::instanceMethod
Constructor Reference(args) -> new Class(args))Class::new

Leave a Reply

Your email address will not be published. Required fields are marked *