运行下面的代码时出现空指针异常:
public class Engine{
private String name = null;
private Mercedes m = null;
private Engine() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Mercedes getM() {
return m;
}
public void setM(Mercedes m) {
this.m = m;
}
public static EngineBuilder builder() {
return new EngineBuilder();
}
public static class EngineBuilder {
private Engine e = null;
public EngineBuilder builder() {
e = new Engine();
return this;
}
public Engine build() {
return this.e;
}
public EngineBuilder setName(String name) {
this.e.setName(name);
return this;
}
public EngineBuilder setM(Mercedes m) {
this.e.setM(m);
return this;
}
}
public static void main(String[] args) {
EngineBuilder builder = Engine.builder();
builder.setName("test");
Engine e = builder.build();
}
}
}
我希望Builder模式可以工作,但我得到了
线程“main”中出现异常java.lang.NullPointerException:无法调用“Engine.setName(String)”,因为“this.e”为空
2条答案
按热度按时间pvcm50d11#
在您的代码中,EngineBuilder类只有默认的构造函数,它不会初始化引擎对象。请编写一个初始化所需对象的构造函数。
ssgvzors2#
生成器未正确实现。它应该是这样的(示例仅针对参数名称)