我创建了这个GenericBuilder类(几乎不受How to implement the builder pattern in Java 8?的启发)
.cpp
但是第二个with()方法抛出
不兼容的类型:无法推断类型变量U (参数不匹配; java.lang.Long不是功能接口)
当我执行以下操作时:
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;
}
}
请注意,实体是 Entity 类的实例。