I created this GenericBuilder class (barely inspired by How to implement the builder pattern in Java 8?)
public class GenericBuilder<T> {
private final T instance;
private GenericBuilder(T instance) {
this.instance = instance;
}
public static <T> GenericBuilder<T> of(Supplier<T> instantiator) {
return new GenericBuilder<T>(instantiator.get());
}
public <U> GenericBuilder<T> with(BiConsumer<T, U> consumer,
U value) {
((Consumer<T>) t -> consumer.accept(t, value)).accept(instance);
return this;
}
public <U> GenericBuilder<T> with(BiConsumer<T, U> consumer,
Supplier<U> supplier) {
return with(consumer, supplier.get());
}
public T build() {
return instance;
}
}
But the second with() method throws
incompatible types: cannot infer type-variable(s) U (argument mismatch; java.lang.Long is not a functional interface)
when I execute the following:
GenericBuilder.of(Dto::new)
.with(Dto::setId, entity::getId)
.build();
Notice that entity is an instance of an Entity class.