繁体   English   中英

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

[英]Cannot infer functional interface type Java 8

我有一个工厂(注册表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);
            }
        };
    }

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

您的defaultSupplier方法的参数类型为Class 您不能传递一个lambda表达式,其中需要一个Class 但是你无论如何都不需要那个方法defaultSupplier

由于TestTestWithArgsValidation的子类型,因此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));
    }    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM