非静态方法的Java使用者方法参考
代码段:非静态方法的Java使用者方法参考,java,method-reference,functional-interface,Java,Method Reference,Functional Interface,代码段: class Scratch { Map<ActionType, SomeConsumer<DocumentPublisher, String, String>> consumerMapping = Map.of( ActionType.REJECT, DocumentPublisher::rejectDocument, ActionType.ACCEPT, DocumentPublisher::acceptDocument,
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);
}
类刮擦{
Map consumerMapping=Map.of(
ActionType.REJECT,DocumentPublisher::rejectDocument,
ActionType.ACCEPT,DocumentPublisher::acceptDocument,
ActionType.DELETE,DocumentPublisher::deleteDocument);
私有无效运行过程(文档操作操作){
DocumentPublisher DocumentPublisher=DocumentPublisherFactory.getDocumentPublisher(action.getType);
SomeConsumer=consumerMapping.get(action.getType());
consumer.apply(documentPublisher、“documentName”、“testId1”);
}
专用接口DocumentPublisher{
作废拒绝文档(字符串名称、字符串textId);
作废接受文档(字符串名称、字符串文本ID);
作废删除文档(字符串名称、字符串文本ID);
}
}
我可以使用哪种类型的功能界面来代替某些消费者?这里的主要问题是它不是静态字段,我只在运行时知道对象
我尝试使用BiConsumer,但它告诉我,我不能以这种方式引用非静态方法。从您在这里的用法:
consumer.apply(documentPublisher, "documentName", "testId1");
很明显,消费者消费了3样东西,因此它不是一个双消费者。您需要一个TriConsumer
,它在标准库中不可用
您可以自己编写这样的功能接口:
interface TriConsumer<T1, T2, T3> {
void accept(T1 a, T2 b, T3 c);
}
根据您在此处的用法:
consumer.apply(documentPublisher, "documentName", "testId1");
很明显,消费者消费了3样东西,因此它不是一个双消费者。您需要一个TriConsumer
,它在标准库中不可用
您可以自己编写这样的功能接口:
interface TriConsumer<T1, T2, T3> {
void accept(T1 a, T2 b, T3 c);
}