假设您有以下课程:
public class MyClass {
public MyClass() {
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在构造函数中传递可定义的参数,如下所示:
public MyClass(int parameters, int /* "parameters" amount of integers here*/) {
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用省略号运算符,但是构造函数将接受比int"parameters"更多或更少的参数.有没有办法做到这一点?
您不能在Java编译器中强制执行此限制,但可以通过抛出以下内容将其强制执行IllegalArgumentException:
public MyClass(int numParameters, int... parameters) {
if (numParameters != parameters.length)
throw new IllegalArgumentException("Number of parameters given doesn't match the expected amount of " + numParameters);
// Rest of processing here.
}
Run Code Online (Sandbox Code Playgroud)
这使用Java的varargs功能来接受未知数量的参数.
注意:为了清楚起见,我重新命名了一些参数.