What is Double Brace initialization syntax ({{ ... }}
) in Java?
To avoid all negative effects of double brace initialization, such as:
do next things:
Example:
public class MyClass {
public static class Builder {
public int first = -1 ;
public double second = Double.NaN;
public String third = null ;
public MyClass create() {
return new MyClass(first, second, third);
}
}
protected final int first ;
protected final double second;
protected final String third ;
protected MyClass(
int first ,
double second,
String third
) {
this.first = first ;
this.second= second;
this.third = third ;
}
public int first () { return first ; }
public double second() { return second; }
public String third () { return third ; }
}
Usage:
MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
Advantages:
Disadvantages:
And, as a result, we have simplest java builder pattern ever.
See all samples at github: java-sf-builder-simple-example