我在以下类中创建修改的 setter :
public class Example {
private String name;
private Integer id;
...
public Example withName(String name) {
this.name = name;
return this;
}
public Example withID(Integer id) {
this.id = id;
return this;
}
...
}
因此实例的初始化变得更加清晰(您可以看到您设置的字段,而无需重复实例名称):
Example example =
new Example()
.withName("Walter")
.withID(23);
是intellij-idea有重构/代码构造方法来自动构建类的链接初始化吗?
最佳答案
您可以使用代码|生成...
自动创 build 置器。首先将字段添加到类中:
class Example {
private String name;
private Integer id;
}
现在调用Code |生成...
(在 Mac 上为 Cmd+N)并选择 Setter
。在出现的对话框顶部选择模板Builder
。选择要为其生成 setter 的字段,然后单击确定
。
结果:
class Example {
private String name;
private Integer id;
public Example setName(String name) {
this.name = name;
return this;
}
public Example setId(Integer id) {
this.id = id;
return this;
}
}
如果您希望 setter 方法以 with
开头,而不是 set
,则可以修改模板。
关于java - Intellij Idea 自动创建类的链接 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54455952/