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 Naor-Reingold Pseudo Random Function
Concrete Class in Java
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Java Program to Compare Binary and Sequential Search
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Using a List of Values in a JdbcTemplate IN Clause
Spring Security Registration – Resend Verification Email
Sorting Query Results with Spring Data
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Spring Security 5 – OAuth2 Login
Java Program to Implement Stack
Java Program to Perform Finite State Automaton based Search
Entity To DTO Conversion for a Spring REST API
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
TreeSet và sử dụng Comparable, Comparator trong java
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
New Features in Java 9
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Implementing a Runnable vs Extending a Thread
Hướng dẫn Java Design Pattern – Memento
Examine the internal DNS cache
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Spring Security Basic Authentication
Spring Security Form Login
Comparing Objects in Java
Java Program to Find the Mode in a Data Set
Java Program to Implement Bellman-Ford Algorithm
Java Program to Implement Vector API
Anonymous Classes in Java
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
The Modulo Operator in Java

1 Trackback / Pingback

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

Comments are closed.