如何自定义 Eclipse 的 getter 和 setter 生成?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/977983/
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
How can I customize Eclipse's getter and setter generation?
提问by Rich Kroll
How can I configure Eclipse to generate getters and setters with some prefix for argument variable?
如何配置 Eclipse 以生成带有参数变量前缀的 getter 和 setter?
Example:
例子:
private String someVariable;
public void setSomeVariable(String aSomeVariable) {
this.someVariable = aSomeVariable;
}
回答by Rich Kroll
You can update all generated variables with a prefix by going to preferences > java > Code Style and selecting Parameters then edit. You can add a prefix/suffix for all generated variable names.
您可以通过转到首选项 > java > 代码样式并选择参数然后编辑来更新带有前缀的所有生成的变量。您可以为所有生成的变量名称添加前缀/后缀。
回答by akf
there are two thing that you need to do to effect the setter in your example.
first, as others have mentioned, you will need to go to the Preferences dialog and go to Java/Code Style/Code Templates/Code/Setter body. in the Pattern box, you should make the value to look like this:
您需要做两件事来影响示例中的 setter。
首先,正如其他人提到的,您需要转到“首选项”对话框并转到“Java/代码样式/代码模板/代码/Setter 主体”。在 Pattern 框中,您应该使值看起来像这样:
this.${field} = ${param};
this.${field} = ${param};
second, still in the Preferences dialog, go up a level to Code Style. Here you will see a table 'Conventions for variable names.' Select the Parameters row and select edit. add the letter a
to the prefix field.
其次,仍然在首选项对话框中,上一级代码样式。在这里,您将看到一个表“变量名称的约定”。选择参数行并选择编辑。将字母添加a
到前缀字段。
Once all of that is saved, you should be able to automatically generate setters as you have defined above, using the Generate Getter and Setter" command.
保存所有这些后,您应该能够使用“生成 Getter 和 Setter”命令自动生成上面定义的 setter。
回答by Abhishek Nandgaonkar
Right click -> Source -> Generate Getters and Setters -> Click on the Code Template link just above the OK button -> Code
右键单击 -> 源代码 -> 生成 Getter 和 Setter -> 单击确定按钮正上方的代码模板链接 -> 代码
I usually write my setter like: if (${param}!=null) ${field} = ${param}; else return new String();
我通常这样写我的 setter: if (${param}!=null) ${field} = ${param}; 否则返回新的字符串();
回答by Ann Addicks
You can select the variable(s) and right click > source > Generate getters and setters. If you only want setters uncheck the getVariable() option.
您可以选择变量并右键单击 > 源 > 生成 getter 和 setter。如果您只想设置器取消选中 getVariable() 选项。