I'm building a JavaBean (only fields and getters/setters) using the builder pattern.
For the sake of this example, assume this is our bean:
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
}
Taken from here.
Now I've been trying to ensure that all of the fields in Pizza
are non-null, with reflection, iterating over the fields of Pizza
and checking they aren't null, but it appears (and I could be wrong here) that my fields aren't set before the check occurs. This code by Jon Skeet is what I altered to check the non-nullness of my fields (and instead of counting, I'm throwing exceptions).
I then tried to check the fields of my builder instead, but I have extra fields in the builder (for instance, I have an XMLParser field which may be null). Subsetting the builder fields by the pizza fields doesn't work as they have different 'package paths' (?), e.g. org.GiusepesPizzaria.pizza.size
vs org.GiusepesPizzaria.builder.size
Is there a better way to check this? Before implementing the reflection method, I used this sort of construct:
if(builder.size ==null){
throw new BadPizzaException("Eh, what're ya doin'?"+
" Pizza Size was not set correctly");
}else{
size=builder.size;
}
But it ends up, if you have say ~10 fields to check, long winded, and clutters what should be a simple class.
So that's what I've tried. Is there a better method?