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
說明如下:
parameters是函式的引數串列
當引數不止一個時,()不可省略,否則可以省略()和型別;
當函式式介面中抽象方法的引數串列的引數型別可以自動推斷時,可以省略對應的型別statements是執行陳述句
當函式體僅有一個陳述句,可以省略{},否則不可省略;expression是運算式
當函式體只有一個運算式,且運算結果匹配回傳值型別,可以省略return關鍵字->是使用指定引數去完成某個功能,不可省略
常見的函式式介面
- 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),它傳入一個泛型引數并回傳true或 false,
案例
給定一個字串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;
}
}
注意:
- 這里的抽象方法是
apply,可以從數學上理解Function介面,即\(f:T \rightarrow R\),輸入一個\(T\)可以回傳一個\(R\),\(f\)就是定義的一套規則,交由apply執行, - 對于
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所示:

詳細程序分析
通過反編譯得到位元組碼檔案,可以分析Lambda運算式的本質,將cfr-0.145.jar包添加到LambdaPrinciple類的編譯路徑,如圖2所示,

執行反編譯命令:java -jar cfr-0.145.jar LambdaPrinciple.class --decodelambdas false,如圖3所示,

得到反編譯的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
標籤:其他
