🔥
Caster 開發日誌
  • Java
    • JVM Performance Tool
      • Java Debug Wire Protocol (JDWP) 的詳細介紹
      • JConsole 詳細介紹
    • Spring Boot
      • Spring Security
      • Spring Boot Admin
      • Spring Event
      • Spring AOP
      • Spring Boot JUnit 5
      • Apache Dubbo
    • Reflect 應用
    • ELK + F 建構
    • Socket.IO
    • OCR - 光學字元辨識
    • 讀取JAR resource文件
    • LocalTime & MySQL時間精度
    • Gradle multi module
    • MyBatis-Plus
    • Java Date operation
    • Java IP to Long
    • Apache Commons lang3 應用
      • Function 應用
    • Cloud Platform
      • Amazon S3
        • SDK V1
          • Bucket
        • SDK V2
          • Bucket
      • Google Cloud Platform
      • Azure Cloud
        • Storage
      • OVHcloud
        • Config
    • SSL/TLS工具
    • Util 工具
      • Jackson Json工具
      • Charles應用
      • JMeter – Performing Distributed Load Testing with Docker
    • Redis
      • Stream
      • Redisson 分布式鎖機制
      • Create Redis Cluster Using Docker
      • List Operations
    • Java 8
      • method & constructor Reference
      • CompletableFuture
      • FunctionInterface
      • Stream 應用
      • 繁簡轉換 - 簡易調整
    • MySQL
      • 建立測試用 流水號Table
      • SQL 效能調校 - Explain
      • SQL 效能調校 - Partition
      • 排程 - Event
    • Apache ShardingSphere
  • Kubernetes
    • 初入江湖(K8S)
    • 零中斷服務滾動更新
    • Kubernetes DNS
    • Ingress & Ingress Controller 教學
    • Ingress TLS Easy setup
  • 指令集
  • Telegram
  • SourceTree
    • 踩坑紀錄(ㄧ) - Git Flow
    • 踩坑紀錄(二) - 修改檔名
  • 專案統計
    • Robot
    • Recharge
  • GitHub
    • Actions
  • GitLab
    • 介紹 GitLab
    • 使用 Docker 自架 GitLab
    • 簡介 GitLab CI/CD
      • GitLab Runner 詳細介紹與設定方式
Powered by GitBook
On this page
  1. Java
  2. Java 8

method & constructor Reference

在Java 8中,引入了方法引用(Method Reference)和构造器引用(Constructor Reference)这两个特性,它们用于简化Lambda表达式,使代码更加清晰易读。

方法引用(Method Reference):

方法引用允许您直接引用现有的方法作为Lambda表达式的替代。语法为類名::方法名,或者是實例::方法名,有以下幾種情況:

  1. 靜態方法引用:使用類名和方法名引用靜態方法。例如:類名::靜態方法名。

  2. 實例方法引用:使用對象實例的方法名引用實例方法。例如:實例::實例方法名。

  3. 特定類型的方法引用:將特定對象的方法引用賦值給通用接口。例如:類型::實例方法名。

  4. 構造器引用:引用構造器,語法為類名::new。例如:ArrayList::new。

構造器引用(Constructor Reference):

構造器引用是方法引用的一個特例,用於創建物件。它類似於靜態方法引用,但語法為類名::new,用來創建與給定類構造函數兼容的物件。

方法引用和構造器引用的優點在於它們可以使代碼更加簡潔易讀,特別是對於一些簡單的操作,可以直接引用已有的方法或構造器,避免了重複編寫相似的Lambda表達式。

以下是一個使用方法引用和構造器引用的簡單示例:

範例一

import java.util.List;
import java.util.ArrayList;

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        
        // 使用方法引用打印每個名字
        names.forEach(System.out::println);
        
        // 使用構造器引用創建一個新的ArrayList物件
        List<String> newList = createList(ArrayList::new);
    }
    
    // 構造器引用示例
    public static <T> List<T> createList(Creator<List<T>> creator) {
        return creator.create();
    }
}

// 自定義的函數式接口,用於創建物件
interface Creator<T> {
    T create();
}

範例二

// 定義車輛工廠介面
interface ICarFactory {
    // 創建車輛物件
    CarBean getCar(String brand, int speed);

    // 靜態方法,打印車輛信息
    static void printCarInfo(CarBean car) {
        System.out.println("Car Name:" + car.getBrand() + " / Max Speed:" + car.getMaxSpeed());
    }
}

// 車輛類別
class CarBean {
    private String brand;
    private int maxSpeed;

    CarBean(String brand, int maxSpeed) {
        this.brand = brand;
        this.maxSpeed = maxSpeed;
    }

    String getBrand() {
        return brand;
    }

    int getMaxSpeed() {
        return maxSpeed;
    }
}

public class MethodAndConstructorReferenceTest {

    public static void main(String[] args) {

        // 測試通過Lambda創建車輛物件
        ICarFactory f = (String name, int maxSpeed) -> new CarBean(name, maxSpeed);
        ICarFactory f_3 = (o1, o2) -> new CarBean(o1, o2);

        // 測試方法引用創建車輛物件
        ICarFactory f_2 = CarBean::new;

        // 創建GTR車輛
        CarBean gtr = f.getCar("GTR", 320);

        // 創建BMW M3車輛
        CarBean m3 = f_2.getCar("BMW_M3", 300);
        
        // 創建Toyota corolla cross車輛        
        CarBean corollaCross = f_3.getCar("Toyota_corolla cross", 200);

        // 遍歷車輛列表,打印車輛信息
        List.of(gtr, m3, corollaCross ).forEach(ICarFactory::printCarInfo);

        // 輸出:
        // Car Name:GTR / Max Speed:320
        // Car Name:BMW_M3 / Max Speed:300
        // Car Name:Toyota_corolla cross / Max Speed:200
    }
}

總之,方法引用和構造器引用是Java 8引入的便利特性,使得代碼更加簡潔和可讀,尤其是在處理一些常見操作時。它們是函數式編程風格的重要組成部分,可以大大提高代碼的可維護性和可讀性。

PreviousJava 8NextCompletableFuture

Last updated 1 year ago