It would be great to make a implementation of the builder pattern with generics. In theory it would be possible to use reflection to make the following possible:
MyClass myClass = GenericBuilder<MyClass>.aObject()
.withThisProperty("foo")
.withThatProperty(4)
.build();
I already made the following code:
public class CursistBuilder {
private Cursist cursist = null;
private CursistBuilder() {
cursist = new Cursist("username not set", "email not set");
}
public static CursistBuilder aCursist() {
return new CursistBuilder();
}
public CursistBuilder withNaam(String name) {
cursist.setGebruikersnaam(name);
return this;
}
public CursistBuilder withEmail(String email) {
cursist.setEmail(email);
return this;
}
public Cursist build() {
return cursist;
}
}
How can this be accomplished?
I do not know this is what you wanted, however if I were you I will implement like below//
main >>
VO >>
I overriden toString() to show what is in it, and declare a Map to assign value to somewhere, if you want you can change this with other Collections. Thanks/
it is not proper builder pattern, as object is not created in
create
function, but you could use it as reference for improvementhow to use it: yo are creating instance of builder by passing class to constructor
Builder<MyClass> builder = new Builder<>(MyClass.class);
and then use method
setProperty(String name, Object value)
to call setter on your object,what you coul done? for example pass some default values for your class and dont use non-args constructor