How to use a nested Java Builder Class to construct an object?
6 views (last 30 days)
Show older comments
I'm currently trying to import and use a class that uses the Java Builder pattern and I can't seem to figure out how to instantiate an instance of the object. Below is my class setup and how I'd build it in Java for reference.
package testJavaBuilder;
public class NutritionalFacts {
private int sodium;
private int fat;
private int carbo;
public static class Builder {
private int sodium;
private int fat;
private int carbo;
public Builder(int s) {
this.sodium = s;
}
public Builder fat(int f) {
this.fat = f;
return this;
}
public Builder carbo(int c) {
this.carbo = c;
return this;
}
public NutritionalFacts build() {
return new NutritionalFacts(this);
}
}
private NutritionalFacts(Builder b) {
this.sodium = b.sodium;
this.fat = b.fat;
this.carbo = b.carbo;
}
}
NutritionalFacts facts = new NutritionalFacts.Builder(10).carbo(23).fat(1).build();
1 Comment
Andrew Janke
on 28 Jul 2017
See https://www.mathworks.com/matlabcentral/answers/98620-how-do-i-create-an-instance-of-a-java-public-static-nested-class-from-inside-matlab-7-13-r2011b. You have to work around this by using Java Reflection calls or writing a custom Java adapter class.
Answers (0)
See Also
Categories
Find more on Call Java from MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!