I’m trying out Effective Java book and enjoying it. I read Builder pattern and I tried to play with it. I have a code like this (in 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
}
}
}
But I get error like this :
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)
I don’t know why this happens! Where I went wrong?
This is your
build()method:Look at your
Javaclass (not theBuilder) – it doesn’t have any explicitly-declared constructors, so the only constructor it has is the public parameterless one declared automatically for you.You need to move this:
outside the
Builderclass. (I’m slightly surprised Groovy didn’t complain earlier, but I’m pretty sure that’s the problem…)EDIT: Now that it’s not throwing an exception, look at your “setter” methods:
The
version = versionline doesn’t do anything. You need to differentiate between the parameter and the field, e.g.… or by giving the parameter a different name, e.g.