是否可以在没有输入参数的地方调用Function和Consumer?我尝试使用关键字void和Void,但它们没有成功。
在下面的代码示例中,如果取消注释methodRef2和methodRef4,则会出现语法错误。
import java.util.function.Function;
import java.util.function.Consumer;
public class StackOverflowExample {
public static void main(String[] args) {
Function<Integer, Integer> methodRef1 = StackOverflowExample::inIntegerOutInteger;
methodRef1.apply(1000);
// Function<void, Integer> methodRef2 = StackOverflowExample::inVoidOutInteger;
// methodRef2.apply();
Consumer<Integer> methodRef3 = StackOverflowExample::inIntegerOutVoid;
methodRef3.accept(45);
// Consumer<void> methodRef4 = StackOverflowExample::inVoidOutVoid;
// methodRef4.accept();
}
protected static int inIntegerOutInteger(int i) {
System.out.println("inIntegerOutInteger invoked with value " + i);
return i;
}
protected static void inIntegerOutVoid(int i) {
System.out.println("inIntegerOutVoid invoked with value " + i);
}
protected static int inVoidOutInteger() {
int retVal = 1000;
System.out.println("inVoidOutInteger invoked: returning value " + retVal);
return retVal;
}
protected static void inVoidOutVoid() {
System.out.println("inVoidOutVoid invoked");
}
}