2017-04-24 66 views
6

我有一个工厂(注册DP)的初始化类:无法推断功能接口类型JAVA 8

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

您拉姆达抛出,并在每个分支不返回的事实可能混淆它。我似乎回想起由于这个原因编写我自己的功能界面。 – Carcigenicate

回答

7

您的defaultSupplier方法的参数类型为Class。您无法在需要Class的地方传递lambda表达式。反正你不需要那种方法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)); 
    }  
}