2017-04-24 67 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)); 
    }  
}