【问题标题】:Java Consumer MethodReference for nonstatic methods非静态方法的 Java Consumer MethodReference
【发布时间】:2020-08-26 02:11:22
【问题描述】:

代码sn-p:

class Scratch {

Map<ActionType, SomeConsumer<DocumentPublisher, String, String>> consumerMapping = Map.of(
        ActionType.REJECT, DocumentPublisher::rejectDocument, 
        ActionType.ACCEPT, DocumentPublisher::acceptDocument,
        ActionType.DELETE, DocumentPublisher::deleteDocument);
        

private void runProcess(DocumentAction action) {
    DocumentPublisher documentPublisher = DocumentPublisherFactory.getDocumentPublisher(action.getType);

    SomeConsumer<DocumentPublisher, String, String> consumer = consumerMapping.get(action.getType());
    consumer.apply(documentPublisher, "documentName", "testId1");
}

private interface DocumentPublisher {
    
    void rejectDocument(String name, String textId);

    void acceptDocument(String name, String textId);

    void deleteDocument(String name, String textId);
}

}

我可以使用哪种类型的功能接口来代替 SomeConsumer?这里的主要问题是它不是静态字段,并且我只会在运行时知道的对象。

我尝试使用 BiConsumer,但它告诉我不能以这种方式引用非静态方法。

【问题讨论】:

    标签: java method-reference functional-interface


    【解决方案1】:

    从你这里的使用来看:

    consumer.apply(documentPublisher, "documentName", "testId1");
    

    很明显,消费者消费了 3 样东西,所以它不是BiConsumer。你需要一个TriConsumer,它在标准库中不可用。

    您可以自己编写这样的功能接口:

    interface TriConsumer<T1, T2, T3> {
        void accept(T1 a, T2 b, T3 c);
    }
    

    如果您要为其提供的唯一通用参数是&lt;DocumentPublisher, String, String&gt;,我认为您应该将其命名为特定于您的应用程序的名称,例如DocumentPublisherAction

    interface DocumentPublisherAction {
        void perform(DocumentPublisher publisher, String name, String textId);
    }
    
    Map<ActionType, DocumentPublisherAction> consumerMapping = Map.of(
            ActionType.REJECT, DocumentPublisher::rejectDocument, 
            ActionType.ACCEPT, DocumentPublisher::acceptDocument,
            ActionType.DELETE, DocumentPublisher::deleteDocument);
            
    
    private void runProcess(DocumentAction action) {
        DocumentPublisher documentPublisher = DocumentPublisherFactory.getDocumentPublisher(action.getType);
    
        DocumentPublisherAction consumer = consumerMapping.get(action.getType());
        consumer.perform(documentPublisher, "documentName", "testId1");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      相关资源
      最近更新 更多