lambda表達式原理砂竖,在類中新增1個私有靜態(tài)類,方法名為lambda$方法名$index
public void method() {
List<Integer> list = Arrays.asList(1);
list.forEach(item -> {
item = item + 1;
System.out.println(item);
});
}
通過javap -c -private XX.class查看字節(jié)碼
public void method();
Code:
0: iconst_1
1: anewarray #5 // class java/lang/Integer
4: dup
5: iconst_0
6: iconst_1
7: invokestatic #6 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
10: aastore
11: invokestatic #7 // Method java/util/Arrays.asList:([Ljava/lang/Object;)Ljava/util/List;
14: astore_1
15: aload_1
16: invokedynamic #8, 0 // InvokeDynamic #0:accept:()Ljava/util/function/Consumer;
21: invokeinterface #9, 2 // InterfaceMethod java/util/List.forEach:(Ljava/util/function/Consumer;)V
26: return
private static void lambda$method$0(java.lang.Integer);
Code:
0: aload_0
1: invokevirtual #10 // Method java/lang/Integer.intValue:()I
4: iconst_1
5: iadd
6: invokestatic #6 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
9: astore_0
10: getstatic #11 // Field java/lang/System.out:Ljava/io/PrintStream;
13: aload_0
14: invokevirtual #12 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
17: return
}
多了1個方法鹃答,private static void lambda$method$0(java.lang.Integer);
如果新增lambda$method$0
一個方法乎澄,代碼無法編譯過
private static void lambda$method$0(Integer item) {
System.out.println(item);
}