我正在尝试有效的Java书并享受它。我读了Builder模式,我试着玩它。我有这样的代码(在Groovy中):
public class Anto {
public static void main(String[] args) {
def testing = new Java.Builder(1).author("antoaravinth").build()
println testing.author
}
}
class Java {
int version
def author
int release_number
public static class Builder {
int version
def author = ""
int release_number = 0
public Builder(int version) {
this.version = version
}
public Builder version(int version)
{
version = version
return this
}
public Builder author(def author)
{
author = author
return this
}
public Builder release_number(int release_number)
{
release_number = release_number
return this
}
public Java build() {
return new Java(this);
}
private Java(Builder builder)
{
version = builder.version
author = builder.author
release_number = builder.release_number
}
}
}
但我得到这样的错误:
Caught: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Java(Java$Builder)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Java(Java$Builder)
at Java$Builder.build(Anto.groovy:43)
at Java$Builder$build.call(Unknown Source)
at Anto.main(Anto.groovy:4)
我不知道为什么会这样!哪里出错了?
答案 0 :(得分:5)
这是您的build()
方法:
public Java build() {
return new Java(this);
}
查看你的Java
类(不是Builder
) - 它没有任何显式声明的构造函数,所以它唯一的构造函数是为你自动声明的public parameterless。 / p>
你需要移动它:
private Java(Builder builder)
{
version = builder.version
author = builder.author
release_number = builder.release_number
}
在Builder
课程之外。 (我有点惊讶Groovy之前没有抱怨,但我很确定这是问题......)
编辑:既然它没有抛出异常,请查看“setter”方法:
public Builder version(int version)
{
version = version
return this
}
version = version
行没有做任何事情。您需要区分参数和字段,例如
public Builder version(int version)
{
this.version = version
return this
}
...或者给参数指定一个不同的名称,例如
public Builder version(int value)
{
version = value
return this
}