具有非静态上下文的 Invokedynamic

Invokedynamic with non-static context

我了解到 invokedynamic 字节码指令调用 lambda 的 static 方法表示。

如果不正确,请告诉我。

如果正确,那么下面的代码是如何工作的?

String[] arr = new String[1];
Stream.of(arr).forEach((s) -> System.out.println(this));

说 lambda 表达式总是 编译成 static 方法是不正确的。没有指定它们是如何编译的,这为捕获 this 的 lambda 表达式留下了两种不同的策略空间,就像您的 s -> System.out.println(this).

  1. 使用实例方法:

    private void compiler$chosen$name(String s) {
        System.out.println(this);
    }
    
  2. 使用static方法:

    private static void compiler$chosen$name(TypeOfThis var0, String s) {
        System.out.println(var0);
    }
    

invokedynamic 指令指向 LambdaMetafactory. In either case, the invokedynamic instruction will have a signature consuming a TypeOfThis instance and producing a Consumer<String>. From the documentation of the LambdaMetafactory 中的 bootstrap 方法时,这两种方法同样有效,您可以推导出它将处理非 [=] 的接收者13=] 目标方法就像一个隐含的第一个参数,这使得两个变体的功能签名相同。重要的是,消费者的 accept 方法的参数必须对应于列表的 last 参数。

我在实践中遇到过这两种策略,所以这确实取决于编译器。

请注意,当使用方法引用时,这些策略也适用于源代码级别:

public class Example {
    BiConsumer<Example,String> variant1 = Example::instanceMethod;
    BiConsumer<Example,String> variant2 = Example::staticMethod;

    private void instanceMethod(String s) {
        System.out.println(this);
    }

    private static void staticMethod(Example instance, String s) {
        System.out.println(instance);
    }
}

这证明了方法接收器和 static 方法的第一个参数的等价性。但是,在绑定参数时,只有 Consumer<String> c = this::instanceMethod; 可以使用方法引用。 LambdaMetafactory 的其他绑定功能仅供编译器为 lambda 表达式生成的代码使用。