为什么lambda转换需要生成静态方法? [英] Why does lambda translation need generation of a static method?

查看:324
本文介绍了为什么lambda转换需要生成静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Lambda转换是一个两步过程,一个:将lambda放入同一类中的静态方法中。

Lambda translation is a two step process, One: desugaring the lambda into a static method in same class.

public class Main {
    public static void main(String[] args) {
        Runnable r = () -> System.out.println("Hello");
        System.out.println(Arrays.asList(Main.class.getDeclaredMethods()));
    }
}




[ private static void Main.lambda $ main $ 0(),public static void
Main.main(java.lang.String [])]

[private static void Main.lambda$main$0(), public static void Main.main(java.lang.String[])]

两个:生成实现功能接口的类。

Two: generation of a class that implements the Functional Interface.

System.out.println("A class has been generated: " + r.getClass());
System.out.println("That implements a Functional Interface: " + Arrays.asList(r.getClass().getInterfaces()));




已生成一个类:class Main $$ Lambda $ 1/149928006

A class has been generated: class Main$$Lambda$1/149928006

实现功能接口:[interface java.lang.Runnable]

That implements a Functional Interface: [interface java.lang.Runnable]

问题这个静态方法有什么需要?为什么不能将lambda主体直接放入接口方法?类似于:

Question: What is the need of this static method? Why can't the lambda body be put directly into the interface method? Something like:

class Main$$Lambda$1 {
    public void run() {
        /* Lambda body here */
    }
}


推荐答案

除了这里给出的正确答案(因为当前的方案更有效,减少了lambdas的捕获/连接成本并减少代码重复),还有一些其他原因导致您的想法根本没有意义。

In addition to the correct answers given here (because the current scheme is more efficient, reducing capture/linkage costs for lambdas and reducing code duplication), there are a few other reasons why your idea simply doesn't make sense.


  • 字节码首先出现在哪里? lambda代理类是在运行时生成的,而不是在编译时生成的。如果我们将字节码填充到代理类中,它必须来自某个地方。这意味着我们必须将它放入捕获类文件,然后将其复制到代理类中。在这里,它只是生活在捕获类中,我们已经完成了。

  • 访问控制。如果lambda主体调用私有方法怎么办?通过将其伪装到捕获类中,它会自动获取捕获类的访问控制上下文(它在逻辑上是它的一部分。)如果我们将字节码放在代理类中,我们必须做额外的魔术来给它正确的访问控制上下文。

  • Where would the bytecode come from in the first place? The lambda proxy class is generated at runtime, not compile time. If we were to stuff the bytecode into the proxy class, it would have to come from somewhere. That would mean we'd have to put it into the capturing class file and then copy it into the proxy class. Here, it just lives in the capturing class and we're done.
  • Access control. What if the lambda body calls a private method? By desugaring it into the capturing class, it automatically acquires the access control context of the capturing class (which it is logically a part of.) If we put the bytecode in the proxy class, we'd have to do additional magic to give it the right access control context.

这篇关于为什么lambda转换需要生成静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆