Why does lambda translation need generation of a static method?

后端 未结 3 1294
花落未央
花落未央 2020-12-16 12:35

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

public class Main {
    public stat         


        
3条回答
  •  旧巷少年郎
    2020-12-16 13:14

    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.

    • 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.

提交回复
热议问题