Where's the code for a lambda located in a jav

2020-05-01 05:05发布

I've this java source file:

import java.util.function.*;
public class t {
   public static void main(String[] args) {
      Function<Integer,Integer> r = (a) -> a*a+2*a+1;
      System.out.println(r.apply(2));
   }
}

I compile it and it works as expected. Here's the output of javap -c -v t, and I can't find the location of lambda in it. Where's the bytecode which tells the jvm to compute the expression with the input Integer whenever the lambda is envoked?

1条回答
\"骚年 ilove
2楼-- · 2020-05-01 05:28

If you want to see the code of your lambda body a*a+2*a+1, you should call javap -c -v -p t to see also the private methods:

private static java.lang.Integer lambda$main$0(java.lang.Integer);
descriptor: (Ljava/lang/Integer;)Ljava/lang/Integer;
flags: ACC_PRIVATE, ACC_STATIC, ACC_SYNTHETIC
Code:
  stack=3, locals=1, args_size=1
     0: aload_0
     1: invokevirtual #7                  // Method java/lang/Integer.intValue:()I
     4: aload_0
     5: invokevirtual #7                  // Method java/lang/Integer.intValue:()I
     8: imul
     9: iconst_2
    10: aload_0
    11: invokevirtual #7                  // Method java/lang/Integer.intValue:()I
    14: imul
    15: iadd
    16: iconst_1
    17: iadd
    18: invokestatic  #4                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    21: areturn
  LineNumberTable:
    line 4: 0

More detailed answer about the lambda inner implementation is here: How will Java lambda functions be compiled?

查看更多
登录 后发表回答