I am looking for a way to invoke multiple argument methods but using a lambda
construct. In the documentation it is said that lambda
is only usable
You do not need helper methods, multiple interfaces, or any other baggage.
However, since Java varargs are implemented using implicit arrays, your lambda will take a single array argument, and have to handle unpacking the argument array.
You will also have to handle type conversions if your function has arguments that are not all of the same class, with all the inherent danger that entails.
package example;
import java.util.Arrays;
import java.util.List;
public class Main {
@FunctionalInterface
public interface Invoker {
R invoke(T... args);
}
@SafeVarargs
public static void test(Invoker invoker, T...args) {
System.out.println("Test result: " + invoker.invoke(args).toString());
}
public static Double divide(Integer a, Integer b) {
return a / (double)b;
}
public static String heterogeneousFunc(Double a, Boolean b, List c) {
return a.toString() + " " + b.hashCode() + " " + c.size();
}
public static void main(String[] args) {
Invoker invoker = argArray -> Main.divide(argArray[0], argArray[1]);
test(invoker, 22, 7);
Invoker
Output:
Test result: 3.142857142857143
Test result: 1.23456 1231 4
Exception in thread "main" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Double
at example.Main.lambda$main$1(Main.java:27)
at example.Main.test(Main.java:13)
at example.Main.main(Main.java:32)