我正在尝试按照构建器模式实现DTO,但是我有一个错误。
问题:
无法分配最终字段SearchRequestDTO.requestType
无法分配最终字段SearchRequestDTO.requestSubType
为什么在SearchRequestDTO的私有构造函数中出现以下错误:
代码:
public class SearchRequestDTO {
private final String requestType = null;
private final String requestSubType = null;
private SearchRequestDTO(SearchRequestDTOBuilder builder){
this.requestType = builder.requestType ;
this.requestSubType = builder.requestSubType;
}
public String getRequestType() {
return requestType;
}
public String getRequestSubType() {
return requestSubType;
}
public static class SearchRequestDTOBuilder {
private String requestType = null;
private String requestSubType = null;
public SearchRequestDTOBuilder requestType(String requestType){
this.requestType = requestType;
return this;
}
public SearchRequestDTOBuilder requestSubType(String requestSubType){
this.requestSubType = requestSubType;
return this;
}
public SearchRequestDTO build(){
return new SearchRequestDTO(this);
}
}
}
答案 0 :(得分:2)
现在很明显。
private final String requestType;
private final String requestSubType;
private SearchRequestDTO(SearchRequestDTOBuilder builder){
this.requestType = builder.requestType ;
this.requestSubType = requestSubType ;
}
public String getRequestType() {
return requestType;
}
public String getRequestSubType() {
return requestSubType;
}
如果你想拥有最终字段,你必须至少初始化它一次。如果您之前启动它 - 您将遇到编译错误。如果你不启动它 - tou会有编译错误。
答案 1 :(得分:-1)
您已将变量声明为final,这就是您无法覆盖它的原因。您只能在声明期间为其分配值。