计算 Java 中 lambda 函数的变量参数

Count variable parameters of lambda function in Java

如何在初始化可变参数 function/lambda 表达式时计算参数的数量? 或者:如何确定 lambda 表达式的元数?

示例:

public class MathFunction{

  private java.util.function.Function <double[], Double> function = null;
  private int length = 0;

  public MathFunction ( Function <double[], Double> pFunction ){    
    this.function = pFunction;
    this.length = ???
  }
}

现在,如果你像这样初始化一个新的 MathFunction

MathFunction func = new MathFunction((x) -> Math.pow(x[0], x[1]));

如何计算 MathFunction- 构造函数中传递的参数(此处:两个)?

你不能。

MathFunction 声明一个构造函数,该构造函数采用单个参数,即 Function。此函数将对双精度数组和 return a Double 进行操作。但请注意,此函数可以对任意长度的 any 双精度数组进行操作。

函数无法知道数组的长度:它只知道它可以对双精度数组进行操作,无论其长度如何。

考虑这些 lambda:

x -> Math.pow(x[0], x[1])
x -> Math.pow(x[0], x[1]) + x[2]
x -> x[0]

它们都是有效的 lambda,它们都符合相同的 Function<double[], Double> 并且它们都(将)对不同长度的数组进行操作。

您唯一的解决方案是将数组的长度作为第二个参数传递给构造函数。

public MathFunction ( Function <double[], Double> pFunction, int length ){    
    this.function = pFunction;
    this.length = length;
}

顺便说一句,这不叫arity,这个词指的是variable arguments