Intellij Ideas-自动将 final 关键字添加到生成的变量中

新引入的代码约定要求在可能的情况下使用“ final”关键字。

问题是,有没有可能用这个关键字自动生成变量?例如,我选择了一个代码片段:

"bla"+"bla"+"bla"

然后按下 ctrl + alt + v-IDE 会生成如下变量:

String blaString = "bla"+"bla"+"bla";

但我需要它是

final String blaString = "bla"+"bla"+"bla";

附注: 我知道检查和“全部修复”的可能性,但它不能用于所有地方,因为有很多老代码,不应该无缘无故重构。

34698 次浏览

Go to preferences -> Code Style -> Code Generation and enable "Make generated local variables final" in the "Final modifier" section. You can also try searching for "final" in preferences.

In IntelliJ 14.1.3

  1. Preferences > Editor > Code Style > Java
  2. To the far right ,there's a tab called Code Generation
  3. In the section called Final Modifier there are two choices:
    • Make generated local variables final
    • Make generated parameters final

For Windows User;

Go to File -> Settings -> Editor -> Code Style -> Select Preferred Language (Settings0) -> Settings1 -> Make generated local variables final, Make generated parameters final -> Apply -> OK

After selecting "introduce local variable" there is a little gear to the right of the variable name. Click that and check "Declare final". That variable will be marked as final and Intellij will remember your preference until changed.