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

6 visualizaciones (últimos 30 días)
Riley Gibbs
Riley Gibbs el 29 de Jun. de 2015
Comentada: Andrew Janke el 28 de Jul. de 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 comentario
Andrew Janke
Andrew Janke el 28 de Jul. de 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.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Call Java from MATLAB en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by