java lambda表达式

lambda表达式原理,在类中新增1个私有静态类,方法名为lambda$方法名$index
  public void method() {
        List list = Arrays.asList(1);
        list.forEach(item -> {
            item = item + 1;
            System.out.println(item);
        });
    }

通过javap -c -private XX.class查看字节码

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);
  }

你可能感兴趣的:(java lambda表达式)