Java Final - an enduring mystery

后端 未结 4 661
心在旅途
心在旅途 2021-01-15 09:08
suggestBox.addKeyUpHandler( new KeyUpHandler() {
  public void onKeyUp(KeyUpEvent event) {
    if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { 
      String bo         


        
4条回答
  •  花落未央
    2021-01-15 09:41

    It's an inner class, passed into addKeyUpHandler -- all variables referenced outside an inner class need to be declared as final to be used within the inner class. This is because the local class instance must maintain a separate copy of the variable, as it may out-live the function; so as not to have the confusion of two modifiable variables with the same name in the same scope, the variable is forced to be non-modifiable.

    Simply do final {type} {new-varname} = {old-varname}; before calling the method that uses the inner class, and then use {new-varname} inside that.

提交回复
热议问题