无法推断功能接口类型 Java 8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43598714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:35:07  来源:igfitidea点击:

Cannot infer functional interface type Java 8

javalambdajava-8registry

提问by user3407267

I have a factory(Registry DP) which initializes the class:

我有一个初始化类的工厂(注册表 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

And in the 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);
            }
        };
    }

But I keep getting Cannot infer functional interface type Error. What I am doing wrong here ?

但我不断收到无法推断功能接口类型错误。我在这里做错了什么?

采纳答案by Holger

Your defaultSuppliermethod has an argument type of Class. You can't pass a lambda expression where a Classis expected. But you don't need that method defaultSupplieranyway.

您的defaultSupplier方法的参数类型为Class. 您不能在需要 a 的地方传递 lambda 表达式Class。但defaultSupplier无论如何你都不需要那种方法。

Since Testand TestWithArgsare a subtypes of Validation, the lambda expressions () -> new Test()and () -> new TestWithArgs(2,4)are already assignable to Supplier<Validation>without that method:

由于TestTestWithArgs是 的子类型Validation,因此 lambda 表达式() -> new Test()() -> new TestWithArgs(2,4)已经可以在Supplier<Validation>没有该方法的情况下分配给:

public class GenericFactory extends AbstractFactory {
    public GenericPostProcessorFactory() {
        factory.put("Test", () -> new Test());
        factory.put("TestWithArgs", () -> new TestWithArgs(2,4));
    }    
}