有没有办法让 Eclipse 自动使我的所有变量成为最终的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11398194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 18:29:49  来源:igfitidea点击:

Is there a way to have Eclipse automatically make all my variables final?

javaeclipseplugins

提问by Daenyth

I try to avoid having non-final variables when possible, and it would save some typing if Eclipse would automate this for me (also so I don't forget to do it). What I'd like is for it to detect when I add a new variable assignment/declaration statement, and as soon as I finish it, insert the finalmodifier.

我尽量避免使用非最终变量,如果 Eclipse 为我自动执行此操作,它会节省一些输入(因此我不会忘记这样做)。我想要的是让它检测我何时添加新的变量赋值/声明语句,并在我完成后立即插入final修饰符。

Is there a configuration option or lightweight plugin that would accomplish this?

是否有配置选项或轻量级插件可以实现这一点?

回答by dogbane

You can add it as a 'Save Action' so that whenever you save a file, Eclipse will add finalto your variables. This is how:

您可以将其添加为“保存操作”,这样每当您保存文件时,Eclipse 都会添加final到您的变量中。这是如何:

  • Go to Window > Preferences > Java > Editor > Save Actions
  • Tick Additional Actionsand press Configure
  • In the Code Styletab there is a section on Variable declarationsand you can tick Use modifier 'final' where possible. You can choose between private fields, parameters and local variables.
  • 转到窗口 > 首选项 > Java > 编辑器 > 保存操作
  • 勾选附加操作并按配置
  • 代码样式选项卡中有一个关于变量声明的部分,您可以在可能的情况下勾选使用修饰符“最终”。您可以在私有字段、参数和局部变量之间进行选择。

Or you can do the same thing manually (every once in while or for existing code base) via Clean up

或者您可以通过清理手动执行相同的操作(每隔一段时间或针对现有代码库)

回答by YMomb

You can use the right click --> source --> clean-up. You should first define in the Code Formatter part of the preference what you really want to be cleaned.

可以使用右键-->源-->清理。您应该首先在首选项的 Code Formatter 部分定义您真正想要清理的内容。

回答by adranale

CheckstylePlugin can do this for you. You have to setup your checkstyle configuration first then enable checkstyle in your project, and let it change your code upon saving a java file.

Checkstyle插件可以为您做到这一点。您必须首先设置您的 checkstyle 配置,然后在您的项目中启用 checkstyle,并在保存 java 文件时让它更改您的代码。

回答by corsiKa

This may not be the most robust solution but for primitives and/or types you use a lot you could define macros

这可能不是最健壮的解决方案,但对于您经常使用的原语和/或类型,您可以定义宏

int --> final int
byte[] --> final byte[]
List --> final List

I really like the formatter idea too, but then you have to accept every other piece of formatting it has, which can be cumbersome.

我也非常喜欢格式化程序的想法,但是您必须接受它所具有的所有其他格式,这可能很麻烦。