1 java lambda functional-programming java-8 method-reference
我有一个叫做的类Numbers,并且在一些static表示基本操作的方法中,例如加法,减法,乘法,除法.
现在我想创建一个静态方法operate,该方法接收对前面static解释过的方法的引用.我怎样才能做到这一点?
public class Numbers {
public static long addition(long x, long y) {
return x + y;
}
public static long operate(/*a reference to a static method in Numbers class*/,
long x, long y) {
return reference(x, y);
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*lko 11
您可能正在寻找一个BinaryOperator<T>代表对两个相同类型操作数的操作,它T返回与操作数相同类型的结果T:
public static long operate(BinaryOperator<Long> binaryOperator, long x, long y) {
return binaryOperator.apply(x, y);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,方法声明中没有任何方法引用.您应该在那里定义参数类型,稍后您将决定在方法调用期间要传递的实际参数:
匿名类:
operate(new BinaryOperator<Long>() {
public @Override Long apply(Long l1, Long l2) {
return Numbers.addition(l1, l2);
}
}, 2, 2);
Run Code Online (Sandbox Code Playgroud)
一个lambda表达式:
operate((l1, l2) -> Numbers.addition(l1, l2), 2, 2);
Run Code Online (Sandbox Code Playgroud)
或方法参考:
operate(Numbers::addition, 2, 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1896 次 |
| 最近记录: |