General Builder Java Builder Template

I am trying to create a class with many parameters using the Builder pattern, rather than telescoping constructors. I do this as described by Joshua Bloch Effective Java, having a private constructor in a wrapper class and an open static class Builder. The Builder class ensures that the object is in a consistent state before calling the build () function, after which it delegates the construction of the object to the private constructor. In this way,

public class Foo {

    // Many variables

    private Foo(Builder b) {
        // Use all of b variables to initialize self
    }

    public static final class Builder {

        public Builder(/* required variables */) {

        }

        public Builder var1(Var var) {
            // set it
            return this;
        }

        public Foo build() {
            return new Foo(this);
        }

    }

}

Then I want to add type restrictions to some of the variables, and therefore I need to parameterize the class definition. I want the boundaries of the Foo class to be the same as the Builder class.

public class Foo<Q extends Quantity> {

    private final Unit<Q> units;
    // Many variables

    private Foo(Builder<Q> b) {
        // Use all of b variables to initialize self
    }

    public static final class Builder<Q extends Quantity> {
        private Unit<Q> units;

        public Builder(/* required variables */) {

        }

        public Builder units(Unit<Q> units) {
            this.units = units;
            return this;
        }

        public Foo build() {
            return new Foo<Q>(this);
        }

    }

}

, , , , . .

public static final Foo.Builder<Acceleration> x_Body_AccelField =
        new Foo.Builder<Acceleration>()
        .units(SI.METER)
        .build();

units Unit<Acceleration>, Unit<Length>, .

? , .

+5
2

units Builder<Q>, Builder.

+7

@Daniel , - Eclipse. , Quantity, Unit METER, , , :

interface Quantity {
}
class Acceleration implements Quantity {
}
class Length implements Quantity {
}
public class Unit<Q extends Quantity> {
    public static final Unit<Length> METER = new Unit<Length>();
}

public static final Foo.Builder<Acceleration> x_Body_AccelField =
    new Foo.Builder<Acceleration>()
    .units(Unit.METER) // here the compiler complains
    .build();

:

The method units(Unit<Acceleration>) in the type Foo.Builder<Acceleration> is
not applicable for the arguments (Unit<Length>)
0

All Articles