Intellij Idea中定制getter setter的模板
如果不想用lombok, 但是又希望代码尽量简洁, 可以用定制getter和setter方法的方式, 让代码尽量紧凑显示
目标格式
public class DemoClass {
private String columnName;
private String varName;
private Class<?> varType;
private boolean primary;
private boolean autoIncrement;
private boolean sortable;
public String getColumnName() {return columnName;}
public void setColumnName(String columnName) {this.columnName = columnName;}
public String getVarName() {return varName;}
public void setVarName(String varName) {this.varName = varName;}
public Class<?> getVarType() {return varType;}
public void setVarType(Class<?> varType) {this.varType = varType;}
public boolean isPrimary() {return primary;}
public void setPrimary(boolean primary) {this.primary = primary;}
public boolean isAutoIncrement() {return autoIncrement;}
public void setAutoIncrement(boolean autoIncrement) {this.autoIncrement = autoIncrement;}
public boolean isSortable() {return sortable;}
public void setSortable(boolean sortable) {this.sortable = sortable;}
}
设置 getter setter 模板
Alt + Ins, 调出快捷菜单后选择 Getter and Setter, 在对话框里, 选择对应的template, 右侧点开后, 可以新建自己的模板并编辑
将getter生成到一行的模板,
#if($field.modifierStatic)
static ##
#end
$field.type ##
#if($field.recordComponent)
${field.name}##
#else
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
#if ($field.boolean && $field.primitive)
is##
#else
get##
#end
${name}##
#end
() {return $field.name;}
将setter生成到一行的模板
#set($paramName = $helper.getParamName($field, $project))
#if($field.modifierStatic)
static ##
#end
void set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))($field.type $paramName) {##
#if ($field.name == $paramName)
#if (!$field.modifierStatic)
this.##
#else
$classname.##
#end
#end
$field.name = $paramName;}
因为实际的模板, 会跟随着Idea的版本不断变化, 所以上面的模板并非符合所有情况, 建议的修改方式是用IntelliJ Default复制一份在这个基础上改, 如果被条件语句隔开导致换行, 而你又不希望换行的地方, 可以用##
表示不换行.
设置格式避免被格式化自动换行
上面的模板设置完会发现无效, 是因为在写入到编辑器时, 被编辑器的自动格式化换行了. 需要进行以下设置
- 打开设置界面 Settings / Editor / Code Style / Java
- Wrapping and Braces 下, 勾选Keep when reformatting 下
- Line breaks
- Comment at first column
- Control statement in one line
- Simple methods in one line
- Blank Lines, Minimum blank lines 下
- Around method in interface 改为 0
- Around method 改为 0