new*_*dev 5 java methods lambda
我有一堂有很多方法的课程。在另一个类中,我需要编写一个处理输入值的方法。对于该方法,我想传递我想要调用的类的方法。1.8 之后的 Java 如何做到这一点?
已经有类似的问题了,但这些问题通常假设我们可以使用具有单个方法的接口,因此可以使用 lambda 表达式等。
class MyClass {
public Object myToString(String a) {
return new String(a);
}
public Object myToString(String a, String b) {
return new String(a + ", " + b);
}
public Object mySum(int a) {
return new Integer(a);
}
public Object mySum(int a, int b) {
return new Integer(a + b);
}
}
class Test {
public Object handleInputs(MyClass myClass, MethodAsParameter theMethod, List<Object> inputs) {
if (type of inputs are Strings) {
myClass.myToString(inputs.get(0));
} else if (.....) {
myClass.mySum(inputs.get(0));
}
}
}
Run Code Online (Sandbox Code Playgroud)
从 Java 8 开始,您可以使用方法引用。方法引用可以分配给Function<A, B>功能接口变量及其子类。
例如,具有这样签名的方法:
class Test {
public static int DoSomething(String s) {...}
}
Run Code Online (Sandbox Code Playgroud)
可以分配给一个Function<String, Integer>变量,例如:
Function<String, Integer> method = Test::DoSomething;
Run Code Online (Sandbox Code Playgroud)
然后调用:
int result = method.apply("Hello!");
Run Code Online (Sandbox Code Playgroud)
因此,通过对代码进行一些小改进,您就可以将方法用作方法引用并作为参数传递给其他函数。
class MyClass {
public static String myToString(String a, String b) {
return a + ", " + b;
}
//notice the boxing in here
public static int mySum(int a, int b) {
return a + b;
}
//not kind of an revolutionary function, just for demonstration
public static<T> T Invoke(BinaryOperator<T> bo, T o1, T o2) {
return bo.apply(o1, o2);
}
public static void main(String[] args) {
int sum = Invoke(MyClass::mySum, 10, 20);
String str = Invoke(MyClass::myToString, "a", "b");
System.out.println(sum);
System.out.println(str);
}
Run Code Online (Sandbox Code Playgroud)
}
这是一个简单的例子:
public class TestMain {
public static void main(String [] args) {
Long a = 15L, b = 20L;
Long sum = combineTwoNumbers(a, b, (p1, p2) -> p1 + p2);
Long product = combineTwoNumbers(a, b, (p1, p2) -> p1 * p2);
System.out.println("Sum is " + sum);
System.out.println("Product is " + product);
}
public static Long combineTwoNumbers(Long a, Long b, BiFunction <Long, Long, Long> combiner) {
return combiner.apply(a, b);
}
}
Run Code Online (Sandbox Code Playgroud)
这里,函数参数是BiFunction,它在输入中接受两个参数并返回一个输出。具体来说,它需要两个长数字并产生第三个结果。该方法的名称保持通用,以便它可以涵盖可能发生的不同函数的更多实例。在我们的示例中,我们传递了一个和和一个乘积函数,如您所见。