传递函数作为对 Java 中另一个方法的引用
Pass function as reference to another method in Java
我在class ABC中有一个函数,其定义大致如下
Boolean getBool(Value val1, Value val2) {
if (val1.getVal() == val2.getVal()) {
return true;
}
return false;
}
如何将此方法作为对另一个方法的引用传递,比如说 operate() 并从那里调用它。
String operate(<<<Pass getBool method here>>>, Param1) {
val1 = some computations on Param1
val2 = some other computations on Param2
Boolean value = <<<<<Call getBool with val1 and val2 here>>>>>
if (value) { return "Yes"; }
else { return "No"; }
}
请帮忙!!
我已经阅读了几个解决方案,但它们要么通过引用传递带有参数的方法,但类型为 void return,或者通过引用传递没有任何参数和一些 return 类型的方法。
我想通过引用传递一个带有参数的函数,并且有一些 return 类型。
您的方法可以用 Java 8 功能接口 BiFunction<T, U, R>
表示,因为它有两个参数和 returns 一个值。
String operate(BiFunction<Value,Value,Boolean> function, TypeOfParam1 param1, TypeOfParam2 param2) {
val1 = some computations on param1
val2 = some other computations on param2
Boolean value = function.apply(val1,val2);
return value ? "Yes" : "No";
}
并使用方法引用调用 operate
:
ABC abcInstance = ...
String boolString = operate (abcInstance::getBool, param1, param2);
使用双函数 class :
public class Test {
private static Boolean getBool(int val1, int val2) {
if (val1 == val2) {
return true;
}
return false;
}
private static String operate(BiFunction<Integer, Integer, Boolean> fun, int param1, int param2) {
int val1 = param1;
int val2 = param2;
Boolean value = fun.apply(val1, val2);
if (value) {
return "Yes";
} else {
return "No";
}
}
public static void main(String[] args) {
operate(TestStaticReference::getBool, 1, 2);
}
}
我在class ABC中有一个函数,其定义大致如下
Boolean getBool(Value val1, Value val2) {
if (val1.getVal() == val2.getVal()) {
return true;
}
return false;
}
如何将此方法作为对另一个方法的引用传递,比如说 operate() 并从那里调用它。
String operate(<<<Pass getBool method here>>>, Param1) {
val1 = some computations on Param1
val2 = some other computations on Param2
Boolean value = <<<<<Call getBool with val1 and val2 here>>>>>
if (value) { return "Yes"; }
else { return "No"; }
}
请帮忙!! 我已经阅读了几个解决方案,但它们要么通过引用传递带有参数的方法,但类型为 void return,或者通过引用传递没有任何参数和一些 return 类型的方法。 我想通过引用传递一个带有参数的函数,并且有一些 return 类型。
您的方法可以用 Java 8 功能接口 BiFunction<T, U, R>
表示,因为它有两个参数和 returns 一个值。
String operate(BiFunction<Value,Value,Boolean> function, TypeOfParam1 param1, TypeOfParam2 param2) {
val1 = some computations on param1
val2 = some other computations on param2
Boolean value = function.apply(val1,val2);
return value ? "Yes" : "No";
}
并使用方法引用调用 operate
:
ABC abcInstance = ...
String boolString = operate (abcInstance::getBool, param1, param2);
使用双函数 class :
public class Test {
private static Boolean getBool(int val1, int val2) {
if (val1 == val2) {
return true;
}
return false;
}
private static String operate(BiFunction<Integer, Integer, Boolean> fun, int param1, int param2) {
int val1 = param1;
int val2 = param2;
Boolean value = fun.apply(val1, val2);
if (value) {
return "Yes";
} else {
return "No";
}
}
public static void main(String[] args) {
operate(TestStaticReference::getBool, 1, 2);
}
}