Method references

Java Method References

Java provides a new feature called method reference in Java 8.
Method reference is used to refer method of functional interface.
It is compact and easy form of lambda expression.
Each time when you are using lambda expression to just referring a method,
you can replace your lambda expression with method reference.

Types of Method References

  1. Reference to a static method.
  2. Reference to an instance method.
  3. Reference to a constructor.

Reference to a Static Method

You can refer to static method defined in the class.
Following is the syntax and example which describe the process of referring static method.

Syntax

ContainingClass::staticMethodName

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
public class StaticMethodReference {
public static void saySomething(){
System.out.println("This is a static method!");
}
public static void main(String[] args) {
Sayable s = StaticMethodReference::saySomething;
s.say();
}
}

interface Sayable{
void say();
}

Output

This is a static method!

Reference to an Instance Method

like static methods,you can refer instance methods also.

Syntax

containingObject::instanceMethodName

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class InstanceMethodReference{
public void saySomething(){
System.out.println("This is instance method!");
}
public static void main(String[] args) {
Sayable s = new InstanceMethodReference()::saySomething;
s.say();
}
}

interface Sayable{
void say();
}

Output

This is instance method!

Reference to a Constructor

You can refer a construct by using the new keyword.

Syntax

ClassName::new

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello!");
}
}

class Message {
Message(String msg) {
System.out.println(msg);
}

Message(String name, String msg) {
System.out.println(name + msg);
}
}

interface Messageable {
Message getMessage(String msg);
}

Output

Hello!

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022-2023 Ataraxia

请我喝杯咖啡吧~