我在用java为类编写生成器时遇到问题。它总是给我一个错误,说找不到符号。
class Company {
private String name;
private String address;
private String contact;
private int sizeOfEmployee;
private Date createdTime;
@Override
public String toString() {
return "Company{" +
"name='" + name + ''' +
", address='" + address + ''' +
", contact='" + contact + ''' +
", sizeOfEmployee=" + sizeOfEmployee +
", createdTime=" + createdTime +
'}';
}
public static class builder {
private String name;
private String address;
private String contact;
private int sizeOfEmployee;
private Date createdTime;
public builder Name (String name){
this.name = name;
return this;
}
public builder address(String address){
this.address = address;
return this;
}
public builder contact(String contact){
this.contact = contact;
return this;
}
public builder size(int sizeOfEmployee){
this.sizeOfEmployee = sizeOfEmployee;
return this;
}
public builder date(Date createdTime){
this.createdTime = createdTime;
return this;
}
}
}
我想写一个建设者,可以打印出我的公司类。有人能告诉我为什么我的建筑工人不工作吗?我搜索如何编写生成器,并尝试复制该方法。但它在这里不起作用。它给了我一个错误,说错误找不到符号。如果我打电话给
Company abc = Company.builder().name("abc").address("Virginia").createdTime(new Date()).sizeOfEmployee(300).contact("12345").build();
它将打印出
Company{name='abc', address='Virginia', contact='12345', sizeOfEmployee=300, createdTime=Wed Oct 21 11:50:41 EDT 2020}
您正在调用不存在的静态方法生成器'Company.builder(('。你可以这样解决问题:
public class Company {
private String name;
private String address;
public static CompanyBuilder builder() {
return new CompanyBuilder();
}
private static class CompanyBuilder {
private final Company company = new Company();
public CompanyBuilder name(String name){
company.name = name;
return this;
}
public CompanyBuilder address(String address){
company.address = address;
return this;
}
public Company build() {
return company;
}
}
public static void main(String[] args) {
System.out.println(Company.builder().name("name").address("address").build());
}
}
对于java项目,我建议使用Lombok。通过一个注释@Builder,包括Lombok插件和依赖项,您可以解决问题,也可以使用许多功能而不是样板代码。
import lombok.Builder;
import lombok.ToString;
@Builder
@ToString
public class Company {
private String name;
private String address;
public static void main(String[] args) {
System.out.println(Company.builder().name("name").address("address").build());
}
}