我有一个工厂(注册表DP)初始化类:
public class GenericFactory extends AbstractFactory {
public GenericPostProcessorFactory() {
factory.put("Test",
defaultSupplier(() -> new Test()));
factory.put("TestWithArgs",
defaultSupplier(() -> new TestWithArgs(2,4)));
}
}
interface Validation
Test implements Validation
TestWithArgs implements Validation
在AbstractFactory中
protected Supplier<Validation> defaultSupplier(Class<? extends Validation> validationClass) {
return () -> {
try {
return validationClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Unable to create instance of " + validationClass, e);
}
};
}
但我不断得到无法推断功能接口类型错误。我在这里做错了什么?
答案 0 :(得分:8)
您的defaultSupplier
方法的参数类型为Class
。您不能传递一个lambda表达式,其中需要Class
。但是你无论如何都不需要那种方法{.1}。
由于defaultSupplier
和Test
是TestWithArgs
的子类型,因此lambda表达式Validation
和() -> new Test()
已经可以分配给() -> new TestWithArgs(2,4)
方法:
Supplier<Validation>