我正在使用构建器模式,但在设置了它返回的nullpointerException
:
package com.test.sample1;
public class MessageID {
public int BOI1;
public int DOI2;
public int CO3;
public MessageID(int BOI1,int DOI2,int CO3){
this.BOI1=BOI1;
this.DOI2=DOI2;
this.CO3=CO3;
}
public int getBOI1(){
return BOI1;
}
public int getDOI2(){
return DOI2;
}
public int CO3(){
return CO3;
}
}
这是BaseServiceRequest.java ::
package com.test.sample;
import com.test.sample1.MessageID;
public class BaseServiceRequest {
MessageID messageID;
public BaseServiceRequest(BaseServiceRequestBuilder builder) {
this.messageID = builder.messageID;
}
public MessageID getMessageID() {
return messageID;
}
public static class BaseServiceRequestBuilder {
private MessageID messageID;
public BaseServiceRequestBuilder messageID(MessageID messageID) {
this.messageID =messageID;
return this;
}
}
}
这是主类::
package com.test.sample;
import com.test.sample.BaseServiceRequest.BaseServiceRequestBuilder;
import com.test.sample1.MessageID;
public class Wrapper {
static BaseServiceRequestBuilder builder = new BaseServiceRequestBuilder();
static BaseServiceRequest request;
public static void main(String[] args) {
test(builder);
int syso = request.getMessageID().getBOI1();
System.out.println(syso);
}
public static void test(BaseServiceRequestBuilder builder) {
builder.messageID(new MessageID(23, 34, 12));
}
}
我应该在request.getMessageID().getBOI1()
得到23的输出,
但得到一个空指针异常
答案 0 :(得分:4)
那是因为你正在调用builder
的构建方法并抛弃结果。保存结果:
request = builder.messageID(new MessageID(23, 34, 12));
请注意,这不是Builder模式的一个例子;它真的是一个工厂。最有用的Builder类使用流畅的API 来使流程清晰且不易出错,并且Builder对象包含构造新实例所需的中间状态,例如:
request = new BaseServiceRequestBuilder().boi1(23).doi2(34).co3(12).build();
如果您已经拥有MessageID
对象,可能来自某个传入请求,则Builder也可能接受它作为参数:
request = new BaseServiceRequestBuilder().messageID(id).build();