使用IntelliJ IDEA,我想创建一个POJO类,帮助我避免犯愚蠢的错误,以错误的方式获取参数。
我只想创建一个类,声明一些字段,并有一种方便的方法来创建所述类,以减少在创建类时错误地获取相同类型参数的可能性。
从这一点开始:
public class TestObject {
public String x;
public String y;
}
我想生成一些我可以使用的东西,比如:
TestObject o = new TestObject().setX("x").setY("y");
或者这个:
TestObject o = TestObjectBuilder.withX("x").withY("y").build();
以下是我目前为实现这一目标所做的工作。
(1)
利用想法
Generate constructor
,选择所有字段,结果如下:
public class TestObject {
public String x;
public String y;
public TestObject(String x, String y) {
this.x = x;
this.y = y;
}
}
(2)
Refactor Constructor with Builder
,必须选择
Use existing
TestObject
名称输入到字段中,因为为什么不输入,导致:
public class TestObject {
public String x;
public String y;
public TestObject(String x, String y) {
this.x = x;
this.y = y;
}
public TestObject setX(String x) {
this.x = x;
return this;
}
public TestObject setY(String y) {
this.y = y;
return this;
}
public TestObject createTestObject() {
return new TestObject(x, y);
}
}
(3)
手动删除构造函数(因为它的存在拒绝使用默认的ctor)并删除createTestObject()方法(因为它是多余的,Java给了我一个免费的克隆方法)。给我留下这个小小的美丽,这是我首先想要的:
public class TestObject {
public String x;
public String y;
public TestObject setX(String x) {
this.x = x;
return this;
}
public TestObject setY(String y) {
this.y = y;
return this;
}
}
另一件事,我想能够做的是添加字段少pfaffing关于。现在,当我添加一个字段时
generate setter
手动修改结果以与其他设定者保持一致-有更好的方法吗?