How to use a nested Java Builder Class to construct an object?

5 Ansichten (letzte 30 Tage)
Riley Gibbs
Riley Gibbs am 29 Jun. 2015
Kommentiert: Andrew Janke am 28 Jul. 2017
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 Kommentar
Andrew Janke
Andrew Janke am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Call Java from MATLAB finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by