主頁 > 後端開發 > 深入理解Lambda運算式

深入理解Lambda運算式

2022-10-10 06:26:36 後端開發

Lambda運算式初體驗

簡介

Lambda 運算式(lambda expression)是一個匿名函式,Lambda運算式基于數學中的λ演算得名,直接對應于其中的lambda抽象(lambda abstraction),是一個匿名函式,即沒有函式名的函式,Lambda運算式可以表示閉包(注意和數學傳統意義上的不同),

——《百度百科》

Java對于Lambda運算式的支持是從JDK8開始的,它來源于數學中的λ演算,是一套關于函式\(f(x)\)定義、輸入量、輸出量的計算方案,簡化了匿名函式的撰寫,使代碼變得簡潔,
另外,提到Lambda運算式,就不得不提及函式式編程,

函式式編程

函式式編程,或稱函式程式設計泛函編程(英語:Functional programming),是一種編程范式,它將電腦運算視為函式運算,并且避免使用程式狀態以及易變物件,其中,λ演算為該語言最重要的基礎,而且,λ演算的函式可以接受函式作為輸入引數和輸出回傳值,
比起指令式編程,函式式編程更加強調程式執行的結果而非執行的程序,倡導利用若干簡單的執行單元讓計算結果不斷漸進,逐層推導復雜的運算,而不是設計一個復雜的執行程序,
在函式式編程中,函式是頭等物件,意思是說一個函式,既可以作為其它函式的輸入引數值,也可以從函式中回傳值,被修改或者被分配給一個變數,

——《維基百科》

總結函式式編程的特點:

  • 函式是“頭等公民”
  • 可以賦值給變數
  • 可以作為其它函式的引數進行傳遞
  • 可以作為其它函式的回傳值

接下來用一個例子感受一下什么是Lambda運算式,

舉個例子

首先宣告一個介面Factory和一個User類,

public interface Factory {
    Object getObject();
}

public class User {
    private String name;
    private int age;

    public User() {}
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

按照傳統的方式,想要實作Factory介面中的抽象方法,有兩種方法:

  • 子類實作介面
  • 匿名內部類

對于第一種方式,代碼如下:

public class SubClass implements Factory {
    @Override
    public Object getObject() {
        return new User("tom", 20);
    }
}
public class Code01_LambdaTest {
    public static void main(String[] args) {
        // 子類實作介面
        Factory factory = new SubClass();
        System.out.println("user = " + user);
    }
}

對于第二種方式,代碼如下:

public class Code01_LambdaTest {
    public static void main(String[] args) {
        // 匿名內部類
        Factory factory = new Factory() {
            @Override
            public Object getObject() {
                return new User("John", 18);
            }
        };
        System.out.println("user = " + user);
    }
}

分析上面的代碼,發現介面Factory中僅僅只有一個抽象方法,我們的目的是為了獲取User類的物件這么一個簡單的操作,卻需要書寫這么多代碼,最最核心的其實就是這一句return new User("John", 18),有沒有更加簡潔的書寫方式實作上面的需求呢?
第三種方法,就是我們要介紹的Lambda運算式,請看代碼:

public class Code01_LambdaTest {
    public static void main(String[] args) {
        // lambda運算式
        Factory factory = () -> new User("Mike", 30);
        System.out.println("user = " + user);
    }
}

通過對比就會發現,代碼是多么的簡潔高效!

Lambda運算式的語法格式

使用前提

必須要有一個函式式介面有且僅有一個抽象方法的介面,要添加注解@FunctionalInterface

兩種語法格式

  • (parameters) -> {statements}
  • (patameters) -> expression

說明如下:

  1. parameters是函式的引數串列
    當引數不止一個時,()不可省略,否則可以省略()和型別;
    當函式式介面中抽象方法的引數串列的引數型別可以自動推斷時,可以省略對應的型別
  2. statements是執行陳述句
    當函式體僅有一個陳述句,可以省略{},否則不可省略;
  3. expression是運算式
    當函式體只有一個運算式,且運算結果匹配回傳值型別,可以省略return關鍵字
  4. ->是使用指定引數去完成某個功能,不可省略

常見的函式式介面

  • Runnable、Callable
  • Supplier、Consumer
  • Comparator
  • Predicate
  • Function

Lambda運算式應用舉例

注意,以下原始碼是基于Java17的,

Runnable、Callable介面

介面介紹

Java-多執行緒:Callable介面和Runnable介面之間的區別

介面原始碼

package java.lang;

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
package java.util.concurrent;

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

案例

public static void main(String[] args) {
    // 使用匿名內部類的方式實作多執行緒
    new Thread(new Runnable() {
        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            System.out.println("執行緒 " + name + " 已啟動!");
        }
    }).start();
    // 使用Lambda運算式
    new Thread(() -> {
        String name = Thread.currentThread().getName();
        System.out.println("Lambda::執行緒 " + name + " 已啟動!");
    }).start();
}

Supplier、Consumer介面

介面介紹

Supplier介面是一個供給型的介面,需要實作get方法,它更像是一個容器,可以用來存盤資料,然后可以供其他方法使用,
Consumer介面就是一個消費型的介面,通過傳入引數,然后輸出值,Consumer是一個介面,并且只要實作一個accept方法,就可以作為一個消費者輸出資訊,andThen方法的回傳值仍為Consumer介面,因此可以持續消費,

介面原始碼

package java.util.function;

@FunctionalInterface
public interface Supplier<T> {
    T get();
}
package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);

    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

案例

對于Supplier供應商介面,我們求陣列arr中的最大值,

public static void main(String[] args) {
    int[] arr = {1, 5, 7, 9, 2, 4, 6, 8};
    // 獲取陣列的最大值
    Supplier<Integer> supplier = () -> {
        int max = Integer.MIN_VALUE;
        for (int j : arr) {
            if (j > max) max = j;
        }
        return max;
    };
    System.out.println(supplier.get());
}

對于Consumer消費者介面,我們測驗持續消費,

public static void consumer(Consumer<String> first, Consumer<String> sec) {
    first.andThen(sec).accept("Tt");
}

然后在main方法中,先消費一條訊息"hello",接著再消費一條訊息"Tt"

public static void main(String[] args) {
    Consumer<String> consumer = msg -> System.out.println("msg = " + msg);
    consumer.accept("hello");
    consumer(
        consumer,
        s -> System.out.println(s.toUpperCase())
    );
}

程式的運行結果為:

msg = hello
msg = Tt
TT

Comparator介面

介面介紹

Comparator介面是一個專用的比較器,當這個物件不支持自比較或者自比較函式不能滿足要求時,可寫一個比較器來完成兩個物件之間大小的比較,Comparator體現了一種策略模式(strategy design pattern),就是不改變物件自身,而用一個策略物件(strategy object)來改變它的行為,

強行對某個物件collection進行整體排序的比較函式,可以將 Comparator 傳遞給 sort 方法(如 Collections.sort 或 Arrays.sort),從而允許在排序順序上實作精確控制,還可以使用 Comparator 來控制某些資料結構(如有序 set 或有序映射)的順序,或者為那些沒有自然順序的物件 collection 提供排序,
當且僅當對于一組元素 S 中的每個 e1 和 e2 而言,c.compare(e1, e2)==0 與 e1.equals(e2) 具有相等的布林值時,Comparator c 強行對 S 進行的排序才叫做與 equals 一致 的排序,
當使用具有與 equals 不一致的強行排序能力的 Comparator 對有序 set(或有序映射)進行排序時,應該小心謹慎,假定一個帶顯式 Comparator c 的有序 set(或有序映射)與從 set S 中抽取出來的元素(或鍵)一起使用,如果 c 強行對 S 進行的排序是與 equals 不一致的,那么有序 set(或有序映射)將是行為“怪異的”,尤其是有序 set(或有序映射)將違背根據 equals 所定義的 set(或映射)的常規協定,
例如,假定使用 Comparator c 將滿足 (a.equals(b) && c.compare(a, b) != 0) 的兩個元素 a 和 b 添加到一個空 TreeSet 中,則第二個 add 操作將回傳 true(樹 set 的大小將會增加),因為從樹 set 的角度來看,a 和 b 是不相等的,即使這與 Set.add 方法的規范相反,
注:通常來說,讓Comparator也實作 java.io.Serializable 是一個好主意,因為它們在可序列化的資料結構(像 TreeSet 、TreeMap)中可用作排序方法,為了成功地序列化資料結構,Comparator(如果已提供)必須實作Serializable,

——《官方檔案》

這里不得不提Comparable介面:

此介面強行對實作它的每個類的物件進行整體排序,這種排序被稱為類的自然排序,類的compareTo方法被稱為它的自然比較方法,
實作此介面的物件串列(和陣列)可以通過Collections.sort(和Arrays.sort)進行自動排序,實作此介面的可以用作有序映射(實作了SortedMap介面的物件)或有序集合(實作了SortedSet介面的物件)中的元素,無需指定比較器,
建議(雖然不是必需的)最好使自然排序與equals一致,所謂自然排序與equals一致指的是 類A 對于每一個 o1 和 o2 來說,當且僅當 ( o1.compareTo( o2 ) )與 o1.equals( o2 )具有相同的 布林值 時,類A的自然排序才叫做與equals一致,

——《官方檔案》

兩個介面有什么區別?

  • Comparator位于包java.util下,而Comparable位于包java.lang下,
  • Comparable介面將比較代碼寫入需要進行比較類的代碼中,而Comparator介面在一個獨立的類中實作比較,
  • Comparator介面相對更靈活,因為它跟介面實作的類是耦合在一起的,可以通過更換比較器來改變不同的比較規則,
  • Comparable介面強制進行自然排序,而Comparator介面不強制進行自然排序,可以指定排序順序,

介面原始碼

package java.util;

import java.io.Serializable;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.function.ToDoubleFunction;
import java.util.Comparators;

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
    
    boolean equals(Object obj);
    default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }
    default Comparator<T> thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);
        return (Comparator<T> & Serializable) (c1, c2) -> {
            int res = compare(c1, c2);
            return (res != 0) ? res : other.compare(c1, c2);
        };
    }
    ...
}

注意:boolean equals(Object obj);是屬于父類Object的,因此它還是函式式介面,仍然只有一個抽象方法int compare(T o1, T o2);

案例

public static void main(String[] args) {
    String[] arr = {"ab", "c", "d", "go", "bee"};
    Comparator<String> comparator = String::compareTo;
    comparator = Comparator.reverseOrder();
    comparator = (o1, o2) -> o2.length() - o1.length();
    Arrays.sort(arr, comparator);
    System.out.println("arr = " + Arrays.toString(arr));
}

依次運行的結果:

arr = [ab, bee, c, d, go]
arr = [go, d, c, bee, ab]
arr = [bee, go, ab, d, c]

Predicate介面

介面介紹

Predicate介面主要用于流的篩選,給定一個包含若干項的流,Stream 介面的filter方法傳入Predicate 并回傳一個新的流,它僅包含滿足給定謂詞的項,可以使用 lambda 運算式或方法參考來實作boolean test(T t)方法,

介面原始碼

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
    
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
    static <T> Predicate<T> not(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
}

注意:Predicate介面包含的單一抽象方法為boolean test(T t),它傳入一個泛型引數并回傳truefalse

案例

給定一個字串String str = "Hello the world !";判斷是否包含指定的字符,
定義3個方法,分別實作的功能,

public static boolean and(Predicate<String> p1, Predicate<String> p2, String s) {
    return p1.and(p2).test(s);
}
public static boolean or(Predicate<String> p1, Predicate<String> p2, String s) {
    return p1.or(p2).test(s);
}
public static boolean negate(Predicate<String> p, String s) {
    return p.negate().test(s);
}

然后在main方法中呼叫

public static void main(String[] args) {
    String str = "Hello the world !";
    boolean ans;
    ans = and(s -> s.contains("H"), s -> s.contains("w"), str);
    ans = or(s -> s.contains("A"), s -> s.contains("z"), str);
    ans = negate(s -> s.length() < 10, str);
    System.out.println("ans = " + ans);
}

逐一運行,運行結果為:

ans = true
ans = false
ans = true

Function介面

介面介紹

函式式介面(Functional Interface)有且僅有一個抽象方法,但是可以有多個非抽象方法的介面,函式式介面可以被隱式轉換為 Lambda 運算式,
Java 8 中提供了一個函式式介面 Function,這個介面表示對一個引數做一些操作然后回傳操作之后的值,這個介面的有一個抽象方法 apply,這個方法就是表明對引數做的操作,

介面原始碼

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
    
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

注意:

  1. 這里的抽象方法是apply,可以從數學上理解Function介面,即\(f:T \rightarrow R\),輸入一個\(T\)可以回傳一個\(R\)\(f\)就是定義的一套規則,交由apply執行,
  2. 對于andThen方法,它回傳一個組合函式,一個函式的輸出將作為另一個函式的輸入,如果對任一函式的求值引發例外,則將例外拋給組合函式的呼叫方,

案例

接下來用對多項式進行求導的例子進行演示,
對于多項式\(f(x) = 5x^3 + 2x^2 + x + 6\),定義陣列C=[5,2,1,6]表示它的系數,
首先定義一個用于求導數的lambda運算式:

Function<Integer[], Integer[]> d = x -> {
    if (x.length == 1) {
        return new Integer[]{0};
    }
    Integer[] C1 = new Integer[x.length - 1];
    for (int i = 0; i < x.length - 1; i++) {
        C1[i] = x[i] * (x.length - 1 - i);
    }
    return C1;
};

為了方便查看,定義一個列印多項式的方法:

public static void showX(Integer[] C) {
    if (C.length == 1) {
        System.out.println("f(x) = " + C[0]);
        return;
    }
    StringBuilder s = new StringBuilder();
    int size = C.length - 1;
    for (int i = 0; i <= size; i++) {
        int pow = size - i;
        if (C[i] != 0 && pow > 0) {
            if (C[i] != 1) s.append(C[i]);
            if (pow == 1) s.append("x");
            else s.append("x^").append(pow);
            s.append(" + ");
        }
        if (C[i] != 0 && pow == 0) s.append(C[i]);
    }
    System.out.println("f(x) = " + s);
}

接下來就可以在main方法里進行呼叫了,我們可以借助Function介面中的apply方法對多項式進行多次求導,

public static void main(String[] args) {
    // 求多項式二階導數
    // f(x) = 5x^3 + 2x^2 + x + 6
    // 系數 = [5,2,1,6]
    // 冪次 = [3,2,1,0]
    // 預期系數 = [30,4]
    // 預期冪次 = [1,0]
    Integer[] C = {5, 2, 1, 6};
    showX(C);

    // 求一階導數
    Integer[] C1 = d.apply(C);
    showX(C1);
    // 求二階導數
    Integer[] C2 = d.andThen(d).apply(C);
    showX(C2);
    // 求三階導數
    Integer[] C3 = d.andThen(d.andThen(d)).apply(C);
    showX(C3);
}

執行結果:

f(x) = 5x^3 + 2x^2 + x + 6
f(x) = 15x^2 + 4x + 1
f(x) = 30x + 4
f(x) = 30

Lambda的底層實作原理剖析

Lambda運算式的本質

它的本質是函式式介面的匿名子類的匿名物件,底層是依賴ASM技術、由匿名內部類實作的,由于Java是面向物件的語言,因此Lambda運算式是一個語法糖,它不能直接執行,需要轉換成內部類才可以運行,

編譯和運行的程序圖

以下面的代碼舉例:

import java.util.Arrays;
import java.util.List;

public class LambdaPrinciple {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("I", "Love", "You");
        list.forEach(s -> System.out.println(s));
    }
}

上述代碼的編譯和運行程序如圖1所示:
image.png

詳細程序分析

通過反編譯得到位元組碼檔案,可以分析Lambda運算式的本質,將cfr-0.145.jar包添加到LambdaPrinciple類的編譯路徑,如圖2所示,
Snipaste_2022-10-09_14-01-27.png
執行反編譯命令:java -jar cfr-0.145.jar LambdaPrinciple.class --decodelambdas false,如圖3所示,
2.png
得到反編譯的LambdaPrinciple.class

import java.io.PrintStream;
import java.lang.invoke.LambdaMetafactory;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class LambdaPrinciple {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("I", "Love", "You");
        list.forEach((Consumer<String>) LambdaMetafactory.metafactory(
            null, null, null, 
            (Ljava / lang / Object;)V, 
            lambda$main$0(java.lang.String), 
            (Ljava / lang / String;)V)());
    }

    private static /* synthetic */ void lambda$main$0(String s) {
        System.out.println(s);
    }
}

從上面可以看到,Lambda運算式最終被編譯成lambda$main$0靜態方法去執行,
接下來找到LambdaMetafactory.java,看下它的metafactory方法

public final class LambdaMetafactory {
    ...
    // LambdaMetafactory bootstrap methods are startup sensitive, and may be
    // special cased in java.lang.invoke.BootstrapMethodInvoker to ensure
    // methods are invoked with exact type information to avoid generating
    // code for runtime checks. Take care any changes or additions here are
    // reflected there as appropriate.

    /**
     * Facilitates the creation of simple "function objects" that implement one
     * or more interfaces by delegation to a provided {@link MethodHandle},
     * after appropriate type adaptation and partial evaluation of arguments.
     * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
     * call sites, to support the <em>lambda expression</em> and <em>method
     * reference expression</em> features of the Java Programming Language.
     *
     * <p>This is the standard, streamlined metafactory; additional flexibility
     * is provided by {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}.
     * A general description of the behavior of this method is provided
     * {@link LambdaMetafactory above}.
     *
     * <p>When the target of the {@code CallSite} returned from this method is
     * invoked, the resulting function objects are instances of a class which
     * implements the interface named by the return type of {@code factoryType},
     * declares a method with the name given by {@code interfaceMethodName} and the
     * signature given by {@code interfaceMethodType}.  It may also override additional
     * methods from {@code Object}.
     *
     * @param caller Represents a lookup context with the accessibility
     *               privileges of the caller.  Specifically, the lookup context
     *               must have {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess()
     *               full privilege access}.
     *               When used with {@code invokedynamic}, this is stacked
     *               automatically by the VM.
     * @param interfaceMethodName The name of the method to implement.  When used with
     *                            {@code invokedynamic}, this is provided by the
     *                            {@code NameAndType} of the {@code InvokeDynamic}
     *                            structure and is stacked automatically by the VM.
     * @param factoryType The expected signature of the {@code CallSite}.  The
     *                    parameter types represent the types of capture variables;
     *                    the return type is the interface to implement.   When
     *                    used with {@code invokedynamic}, this is provided by
     *                    the {@code NameAndType} of the {@code InvokeDynamic}
     *                    structure and is stacked automatically by the VM.
     * @param interfaceMethodType Signature and return type of method to be
     *                            implemented by the function object.
     * @param implementation A direct method handle describing the implementation
     *                       method which should be called (with suitable adaptation
     *                       of argument types and return types, and with captured
     *                       arguments prepended to the invocation arguments) at
     *                       invocation time.
     * @param dynamicMethodType The signature and return type that should
     *                          be enforced dynamically at invocation time.
     *                          In simple use cases this is the same as
     *                          {@code interfaceMethodType}.
     * @return a CallSite whose target can be used to perform capture, generating
     *         instances of the interface named by {@code factoryType}
     * @throws LambdaConversionException If {@code caller} does not have full privilege
     *         access, or if {@code interfaceMethodName} is not a valid JVM
     *         method name, or if the return type of {@code factoryType} is not
     *         an interface, or if {@code implementation} is not a direct method
     *         handle referencing a method or constructor, or if the linkage
     *         invariants are violated, as defined {@link LambdaMetafactory above}.
     * @throws NullPointerException If any argument is {@code null}.
     * @throws SecurityException If a security manager is present, and it
     *         <a href="https://www.cnblogs.com/aldalee/archive/2022/10/09/MethodHandles.Lookup.html#secmgr">refuses access</a>
     *         from {@code caller} to the package of {@code implementation}.
     */
    public static CallSite metafactory(MethodHandles.Lookup caller,
                                       String interfaceMethodName,
                                       MethodType factoryType,
                                       MethodType interfaceMethodType,
                                       MethodHandle implementation,
                                       MethodType dynamicMethodType)
    throws LambdaConversionException {
        AbstractValidatingLambdaMetafactory mf;
        mf = new InnerClassLambdaMetafactory(Objects.requireNonNull(caller),
                                             Objects.requireNonNull(factoryType),
                                             Objects.requireNonNull(interfaceMethodName),
                                             Objects.requireNonNull(interfaceMethodType),
                                             Objects.requireNonNull(implementation),
                                             Objects.requireNonNull(dynamicMethodType),
                                             false,
                                             EMPTY_CLASS_ARRAY,
                                             EMPTY_MT_ARRAY);
        mf.validateMetafactoryArgs();
        return mf.buildCallSite();
    }
}

接下來看下new InnerClassLambdaMetafactory()的代碼,它的作用是創建內部類

public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
                                   MethodType factoryType,
                                   String interfaceMethodName,
                                   MethodType interfaceMethodType,
                                   MethodHandle implementation,
                                   MethodType dynamicMethodType,
                                   boolean isSerializable,
                                   Class<?>[] altInterfaces,
                                   MethodType[] altMethods)
    throws LambdaConversionException {
    super(caller, factoryType, interfaceMethodName, interfaceMethodType,
        implementation, dynamicMethodType,
        isSerializable, altInterfaces, altMethods);
    implMethodClassName = implClass.getName().replace('.', '/');
    implMethodName = implInfo.getName();
    implMethodDesc = implInfo.getMethodType().toMethodDescriptorString();
    constructorType = factoryType.changeReturnType(Void.TYPE);
    lambdaClassName = lambdaClassName(targetClass);
    // If the target class invokes a protected method inherited from a
    // superclass in a different package, or does 'invokespecial', the
    // lambda class has no access to the resolved method. Instead, we need
    // to pass the live implementation method handle to the proxy class
    // to invoke directly. (javac prefers to avoid this situation by
    // generating bridges in the target class)
    useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
                           !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
        implKind == H_INVOKESPECIAL;
    cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    int parameterCount = factoryType.parameterCount();
    if (parameterCount > 0) {
        argNames = new String[parameterCount];
        argDescs = new String[parameterCount];
        for (int i = 0; i < parameterCount; i++) {
            argNames[i] = "arg$" + (i + 1);
            argDescs[i] = BytecodeDescriptor.unparse(factoryType.parameterType(i));
        }
    } else {
        argNames = argDescs = EMPTY_STRING_ARRAY;
    }
}

值得注意的是cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);,它的作用是構造一個新的ClassWriter物件,寫位元組碼檔案,這其實就是ASM技術
回到LambdaMetafactory.java,查看metafactory方法它的回傳值,走到這一步時,其實準備作業已經完成了,關鍵的代碼是final Class<?> innerClass = spinInnerClass();要回傳內部類的位元組碼檔案,

@Override
CallSite buildCallSite() throws LambdaConversionException {
    final Class<?> innerClass = spinInnerClass();
    if (factoryType.parameterCount() == 0) {
        // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance,
        // unless we've suppressed eager initialization
        if (disableEagerInitialization) {
            try {
                return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
                        factoryType.returnType()));
            } catch (ReflectiveOperationException e) {
                throw new LambdaConversionException(
                        "Exception finding " +  LAMBDA_INSTANCE_FIELD + " static field", e);
            }
        } else {
            @SuppressWarnings("removal")
            final Constructor<?>[] ctrs = AccessController.doPrivileged(
                    new PrivilegedAction<>() {
                        @Override
                        public Constructor<?>[] run() {
                            Constructor<?>[] ctrs = innerClass.getDeclaredConstructors();
                            if (ctrs.length == 1) {
                                // The lambda implementing inner class constructor is private, set
                                // it accessible (by us) before creating the constant sole instance
                                ctrs[0].setAccessible(true);
                            }
                            return ctrs;
                        }
                    });
            if (ctrs.length != 1) {
                throw new LambdaConversionException("Expected one lambda constructor for "
                        + innerClass.getCanonicalName() + ", got " + ctrs.length);
            }

            try {
                Object inst = ctrs[0].newInstance();
                return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
            } catch (ReflectiveOperationException e) {
                throw new LambdaConversionException("Exception instantiating lambda object", e);
            }
        }
    } else {
        try {
            MethodHandle mh = caller.findConstructor(innerClass, constructorType);
            return new ConstantCallSite(mh.asType(factoryType));
        } catch (ReflectiveOperationException e) {
            throw new LambdaConversionException("Exception finding constructor", e);
        }
    }
}

接下來查看spinInnerClass的原始碼

private Class<?> spinInnerClass() throws LambdaConversionException {
    // CDS does not handle disableEagerInitialization.
    if (!disableEagerInitialization) {
        // include lambda proxy class in CDS archive at dump time
        if (CDS.isDumpingArchive()) {
            Class<?> innerClass = generateInnerClass();
            LambdaProxyClassArchive.register(targetClass,
                                             interfaceMethodName,
                                             factoryType,
                                             interfaceMethodType,
                                             implementation,
                                             dynamicMethodType,
                                             isSerializable,
                                             altInterfaces,
                                             altMethods,
                                             innerClass);
            return innerClass;
        }

        // load from CDS archive if present
        Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
                                                           interfaceMethodName,
                                                           factoryType,
                                                           interfaceMethodType,
                                                           implementation,
                                                           dynamicMethodType,
                                                           isSerializable,
                                                           altInterfaces,
                                                           altMethods);
        if (innerClass != null) return innerClass;
    }
    return generateInnerClass();
}

接下來查看generateInnerClass()的原始碼

private Class<?> generateInnerClass() throws LambdaConversionException {
    String[] interfaceNames;
    String interfaceName = interfaceClass.getName().replace('.', '/');
    boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
    if (altInterfaces.length == 0) {
        interfaceNames = new String[]{interfaceName};
    } else {
        // Assure no duplicate interfaces (ClassFormatError)
        Set<String> itfs = new LinkedHashSet<>(altInterfaces.length + 1);
        itfs.add(interfaceName);
        for (Class<?> i : altInterfaces) {
            itfs.add(i.getName().replace('.', '/'));
            accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
        }
        interfaceNames = itfs.toArray(new String[itfs.size()]);
    }

    cw.visit(CLASSFILE_VERSION, ACC_SUPER + ACC_FINAL + ACC_SYNTHETIC,
             lambdaClassName, null,
             JAVA_LANG_OBJECT, interfaceNames);

    // Generate final fields to be filled in by constructor
    for (int i = 0; i < argDescs.length; i++) {
        FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_FINAL,
                                        argNames[i],
                                        argDescs[i],
                                        null, null);
        fv.visitEnd();
    }

    generateConstructor();

    if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
        generateClassInitializer();
    }

    // Forward the SAM method
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, interfaceMethodName,
                                      interfaceMethodType.toMethodDescriptorString(), null, null);
    new ForwardingMethodGenerator(mv).generate(interfaceMethodType);

    // Forward the altMethods
    if (altMethods != null) {
        for (MethodType mt : altMethods) {
            mv = cw.visitMethod(ACC_PUBLIC, interfaceMethodName,
                                mt.toMethodDescriptorString(), null, null);
            new ForwardingMethodGenerator(mv).generate(mt);
        }
    }

    if (isSerializable)
        generateSerializationFriendlyMethods();
    else if (accidentallySerializable)
        generateSerializationHostileMethods();

    cw.visitEnd();

    // Define the generated class in this VM.

    final byte[] classBytes = cw.toByteArray();
    // If requested, dump out to a file for debugging purposes
    if (dumper != null) {
        AccessController.doPrivileged(new PrivilegedAction<>() {
            @Override
            public Void run() {
                dumper.dumpClass(lambdaClassName, classBytes);
                return null;
            }
        }, null,
        new FilePermission("<<ALL FILES>>", "read, write"),
        // createDirectories may need it
        new PropertyPermission("user.dir", "read"));
    }
    try {
        // this class is linked at the indy callsite; so define a hidden nestmate
        Lookup lookup;
        if (useImplMethodHandle) {
            lookup = caller.defineHiddenClassWithClassData(classBytes, implementation, !disableEagerInitialization,
                                                           NESTMATE, STRONG);
        } else {
            lookup = caller.defineHiddenClass(classBytes, !disableEagerInitialization, NESTMATE, STRONG);
        }
        return lookup.lookupClass();
    } catch (IllegalAccessException e) {
        throw new LambdaConversionException("Exception defining lambda proxy class", e);
    } catch (Throwable t) {
        throw new InternalError(t);
    }
}

這里要注意的是dumper,如果請求,轉儲到檔案以進行除錯,點進去,可以得到下面的JVM引數:final String dumpProxyClassesKey = "jdk.internal.lambda.dumpProxyClasses";
然后在LambdaPrinciple位元組碼檔案所在的路徑,繼續反編譯,將內部類轉儲出來,
轉儲命令為:java -Djdk.internal.lambda.dumpProxyClasses LambdaPrinciple,得到LambdaPrinciple$$Lambda$1.class
然后再將其進行反編譯java -jar cfr-0.145.jar LambdaPrinciple$$Lambda$1.class --decodelambdas false,得到如下的結果:

final class LambdaPrinciple$$Lambda$1 implements Consumer {
    private LambdaPrinciple$$Lambda$1() {
    }

    @LambdaForm.Hidden
    public void accept(Object object) {
        LambdaPrinciple.lambda$main$0((String)object);
    }
}

整合上面反編譯的代碼,如下所示:

public class LambdaPrinciple {
    final class LambdaPrinciple$$Lambda$1 implements Consumer {
    private LambdaPrinciple$$Lambda$1() {
    }

    @LambdaForm.Hidden
    public void accept(Object object) {
        LambdaPrinciple.lambda$main$0((String)object);
    }
}
    public static void main(String[] args) {
        List<String> list = Arrays.asList("I", "Love", "You");
        list.forEach((Consumer<String>) LambdaMetafactory.metafactory(
            null, null, null, 
            (Ljava / lang / Object;)V, 
            lambda$main$0(java.lang.String), 
            (Ljava / lang / String;)V)());
    }
	
    private static /* synthetic */ void lambda$main$0(String s) {
        System.out.println(s);
    }
}

至此,便可以清晰的看到Lambda運算式的編譯和運行程序,也更好的理解了Lambda運算式它的本質是函式式介面的匿名子類的匿名物件

本文的所有代碼

可參考:https://github.com/aldalee/java-new-features/tree/master/lambda,稍有改動,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511921.html

標籤:其他

上一篇:面試官:Hash 碰撞是什么?如何解決?被問懵了……

下一篇:SpringMvc(五) - 支付寶沙箱和關鍵字過濾,md5加密,SSM專案重要知識點

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more