Phương thức tham chiếu trong Java 8 – Method References

1. Method References là gì?

Java cung cấp một tính năng mới gọi là Method References (phương thức tham chiếu) trong Java 8.

Method References là một tính năng khá hay và liên quan đến việc sử dụng Lambda Expression. Nó cung cấp các cú pháp (syntax) hữu ích để truy cập trực tiếp tới các constructor hoặc method đã tồn tại của các lớp hoặc đối tượng trong Java mà không cần thực thi chúng. Nó làm cho việc viết code của chúng ta trở nên đơn giản hơn rất nhiều và nhìn chúng đẹp hơn.

Method References là cú pháp viết tắt của biểu thức Lambda để gọi phương thức. Ví dụ, nếu biểu thức Lamda được viết như sau:

str -> System.out.println(str)

Chúng ta có thể viết lại theo cách của Method references như sau:

System.out::println

Java 8 cho phép truyền một tham chiếu của một method hoặc constructor thông qua việc sử dụng từ khóa ::

2. Các loại Method References

  • Tham chiếu đến một static method – Class::staticMethod
  • Tham chiếu đến một instance method của một đối tượng cụ thể – object::instanceMethod
  • Tham chiếu đến một instance method của một đối tượng tùy ý của một kiểu cụ thể – Class::instanceMethod
  • Tham chiếu đến một constuctor – Class::new

2.1. Tham chiếu đến một static method

Cú pháp:

Class::staticMethod

Ví dụ:

package com.maixuanviet.method_reference;
 
@FunctionalInterface
interface ExecuteFunction {
    public int execute(int a, int b);
}
 
class MathUtils {
    public static int sum(int a, int b) {
        return a + b;
    }
 
    public static int minus(int a, int b) {
        return a - b;
    }
}
 
public class DemoMethodReference1 {
    public static void main(String[] args) {
        int a = 10;
        int b = 7;
 
        int sum = doAction(a, b, MathUtils::sum);
        System.out.println(a + " + " + b + " = " + sum); // 10 + 7 = 17
 
        int minus = doAction(a, b, MathUtils::minus);
        System.out.println(a + " - " + b + " = " + minus); // 10 - 7 = 3
    }
 
    public static int doAction(int a, int b, ExecuteFunction func) {
        return func.execute(a, b);
    }
}

Thông qua ví dụ trên, bạn có thể thấy cách thức sử dụng từ khóa :: để truyền vào tham chiếu của một method. Nếu bạn gọi một method, mà trong method đó có một tham số là Functional Interface, bạn có thể truyền vào một tham chiếu method có cấu trúc giống với cấu trúc method định nghĩa trong Functional interface.

2.2. Tham chiếu đến một instance method của một đối tượng cụ thể

package com.maixuanviet.method_reference;
 
@FunctionalInterface
interface ExecuteFunction2 {
    public int execute(int a, int b);
}
 
class MathUtils2 {
    public int sum(int a, int b) {
        return a + b;
    }
 
    public int minus(int a, int b) {
        return a - b;
    }
}
 
public class DemoMethodReference2 {
    public static void main(String[] args) {
        int a = 10;
        int b = 7;
 
        MathUtils2 obj = new MathUtils2();
        int sum = doAction(a, b, obj::sum);
        System.out.println(a + " + " + b + " = " + sum); // 10 + 7 = 17
 
        int minus = doAction(a, b, obj::minus);
        System.out.println(a + " - " + b + " = " + minus); // 10 - 7 = 3
    }
 
    public static int doAction(int a, int b, ExecuteFunction2 func) {
        return func.execute(a, b);
    }
}

Như bạn thấy cách sử dụng hoàn toàn tương tự như tham chiếu đến một static method. Bạn chỉ việc khởi tạo một đối tượng cụ thể và sử dụng cú pháp:

object::instanceMethod

2.3. Tham chiếu đến một instance method của một đối tượng tùy ý của một kiểu cụ thể

Cú pháp:

Class::instanceMethod

Ví dụ:

package com.maixuanviet.method_reference;
 
import java.util.Arrays;
 
public class DemoMethodReference3 {
    public static void main(String[] args) {
        String[] stringArray = { "Java", "C++", "PHP", "C#", "Javascript" };
 
        Arrays.sort(stringArray, String::compareToIgnoreCase);
        for (String str : stringArray) {
            System.out.println(str);
        }
    }
}

2.4. Tham chiếu đến một constuctor

Cú pháp:

Class::new

Ví dụ:

package com.maixuanviet.method_reference;
 
@FunctionalInterface
interface SayHello {
    void display(String say);
}
 
class Hello implements SayHello {
    public Hello(String say) {
        System.out.print(say);
    }
 
    @Override
    public void display(String say) {
        System.out.println(say);
    }
}
 
public class DemoMethodReference4 {
 
    public static void main(String[] args) {
        SayHello ref = Hello::new;
        ref.display("Welcome to maixuanviet.com");
    }
 
}

Như vậy là chúng ta đã tìm hiểu xong một tính năng mới trong Java 8 là Method References. Một vài lưu ý khi về Method References:

  • Chúng ta có thể sử dụng Method References để thay thế cho các Lambda Expression khi Lamba gọi một phương thức nào đó đã được định nghĩa sẵn.
  • Chúng ta không thể truyền tham số cho các Method References, phải sử dụng đi kèm với Functional Interfaces.

Related posts:

Java Program to Implement Graph Structured Stack
Spring Security 5 – OAuth2 Login
Java Program to Implement Karatsuba Multiplication Algorithm
Spring Cloud AWS – S3
Checking for Empty or Blank Strings in Java
The Registration Process With Spring Security
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Spring REST with a Zuul Proxy
Arrays.asList vs new ArrayList(Arrays.asList())
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Java Program to Implement Iterative Deepening
Map to String Conversion in Java
Create Java Applet to Simulate Any Sorting Technique
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Cài đặt và sử dụng Swagger UI
Spring Data Reactive Repositories with MongoDB
Introduction to Spring Data JPA
Introduction to Using Thymeleaf in Spring
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Java Program to Implement Adjacency List
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Implement K Way Merge Algorithm
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Java Program to Implement Hamiltonian Cycle Algorithm
Java Program to Implement the String Search Algorithm for Short Text Sizes
Compare Two JSON Objects with Jackson
Examine the internal DNS cache
Spring Boot - OAuth2 with JWT
Hướng dẫn Java Design Pattern – Flyweight
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Multi Dimensional ArrayList in Java

1 Trackback / Pingback

  1. Function trong Java 8 - Blog của VietMX

Comments are closed.