当前位置:网站首页>Anonymous inner classes and local variables

Anonymous inner classes and local variables

2022-06-09 12:04:00 howeres

Anonymous inner class And local variable

An anonymous class Cannot access... In an external class method local variable , Unless the variable is declared as final type ;

Usually in a method , There are local variables and temporary anonymous classes , When using :

Integer i = 8848;
new Thread(
  () -> {
    
    Integer j = i; //  Report errors  i  Can't use 
    System.out.println("j = " + j);
  })
  .start();
i = 996;

So unless the declared variable i by final ( Or it will not be used later , The compiler will automatically convert to final), Otherwise, you can't operation local variable i .

It's actually the object of the inner class that uses it , It can be called in the life cycle of an inner class object , When an inner class attempts to access a local variable in an outer method , The local variables of the external method probably no longer exist , Then we have to extend its life , Copy to inner class , And copying can lead to inconsistencies , So we need to use final Declaration of conformity .

here , The internal class will automatically copy the external variables References to , for fear of : The reference values obtained by the inner class are inconsistent 、 Internal class modification reference , The parameter values of external methods are inconsistent before and after modification .

If it is a member variable of an external class, it does not need to be final Of , Because the inner class itself will contain a reference to the outer class ( External class .this), Therefore, when callback, you must be able to access .

Anonymous inner class And Member variables

  • Member variables , Through the constructor of anonymous class , Copy the address reference of an instance , To call the instance properties ( The attribute is private It's OK ), It ensures that when the variable changes Consistency of data references , Don't have to add final;
  • Global variables are the same (static), In anonymous inner classes , Variables can be accessed directly through classes , Sure Ensure the consistency of variable references , So don't add final;

Anonymous inner class definition

  • Anonymous inner class : In class Member method Inside , Simultaneous completion Definition and Instantiation Class . Have grammar sugar , The compiler helps create classes , This anonymous name already has a name after compilation , The class name generated by this compilation , To create an object , It is the same as the normal process of implementing classes .
              ch.pipeline()
                      .addLast(
                              new ChannelDuplexHandler() {
    
                                  //  Handle   Other than reading and writing   Special events 
                                  @Override
                                  public void userEventTriggered(
                                          ChannelHandlerContext ctx, Object evt) throws Exception {
    
                                      IdleStateEvent event = (IdleStateEvent) evt;
                                      //  whether   Read timeout 
                                      if (event.state() == IdleState.WRITER_IDLE) {
    
                                          ctx.writeAndFlush(new PingMessage());
                                      }
                                  }
                              });
  						//  Or something like this 
              return ()-> {
    };
  • reason : Difficulties in compiler implementation , Of the inner class object Life cycle Will surpass local variable Life cycle of .

    • The life cycle of a local variable : When the method is called , The local variables in this method are created in the stack , When the method call ends , Backstack , All of these local variables died .
    • The inner class object life cycle is the same as other classes : Create an anonymous inner class object , The system allocates memory for this object , Until no reference variable points to the memory allocated to the object , It will die ( By JVM Garbage collection ).
  • So one situation that is entirely possible is : Member method call ended , The local variable is dead , But objects of anonymous inner classes are still alive . If an object of an anonymous inner class accesses a local variable in the same method , It requires that as long as the anonymous inner class object is alive , Then the local variables in the stack that it wants to access cannot “ Death ”.

The process

Anonymous inner class objects accessing the same method are defined as final Type of local variable . Defined as final after , Implementation method of compiler : For all anonymous inner class objects to access final Type local variables , Are copied as a data member of the object . such , Even in the stack The local variable is dead , But it is defined as final The value of a local variable of type never changes , Therefore, the anonymous inner class object after the local variable dies , You can still access final Type of local variable , Because it itself Made a copy of , And it is always consistent with the value of the original local variable .

原网站

版权声明
本文为[howeres]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091123594261.html