I have created a Bean Class using Builder Pattern and having issues creating an object from a yaml file.
Here is a sample class (Actual class is quite big, this is just an excerpt incase if you wanted to answer with an example):
public class ClientBuilder {
private final String firstName;
private final String lastName;
private final String displayName;
private ClientBuilder(Builder builder) {
firstName = builder.firstName;
lastName = builder.lastName;
displayName = builder.displayName;
}
public static class Builder {
private final String displayName; // Mandatory Attribute
public Builder( String displayName ) {
this.displayName = displayName;
}
private String firstName;
private String lastName;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public ClientBuilder build() {
return new ClientBuilder(this);
}
}
@Override
public String toString() {
StringBuffer sbf = new StringBuffer();
sbf.append("New Company Object: \n");
sbf.append("firstName : " + this.firstName + "\n");
sbf.append("lastName : " + this.lastName + "\n");
sbf.append("displayName : " + this.displayName + "\n");
return sbf.toString();
}
}
I am using snakeyaml to load the file but any yaml api would work. Since the displayName
is a mandatory param, I want to pass that value while creating the instance. The other params can be passed while creating the object but I would like the option to load them through yaml file.
I am able to load the yaml file if I use java bean. Is there a way to instantiate builder objects?
I tried:
InputStream input = new FileInputStream(new File("src/main/resources/client.yaml"));
Yaml yaml = new Yaml();
Builder builder = new Builder("Display Name");
builder = (Builder) yaml.loadAs(input, ClientBuilder.Builder.class);
ClientBuilder client = builder.build();
System.out.println(client.toString());
but I get following error:
Exception in thread "main" Can't construct a java object for tag:yaml.org,2002:com.xxx.xxx.xxx.ClientBuilder$Builder; exception=java.lang.NoSuchMethodException: com.xxx.xxx.xxx.ClientBuilder$Builder.<init>()
in 'reader', line 2, column 1:
firstName: "Jaypal"