This question already has an answer here:
I want to force the user to fill in an optional parameter when calling my constructor:
public MyClass(String... params) {
this.params = params;
}
Currently, the following code is valid:
new MyClass();
I want to prevent it. I thought of this:
public MyClass(String param1, String... otherParams) {
this.params = new String[1 + otherParams.length];
this.params[0] = param1;
// fill 1..N params from otherParams
}
String[] params
is not an option, because I need the ability to use comma separated args.
Are there any nice solutions to achieve this? Please don't say that varargs parameters must be optional. The question is not about that.
Maybe the following, an extra default constructor?
/**
* Please provide at least one parameter.
*/
@Deprecated
public MyClass() {
throw new IllegalStateException("Please provide at least one parameter");
}
No, there's no other way to do this at compile-time. What you found is the usual pattern of forcing the client code to pass at least one parameter.
You can read it like this:
// You can pass in some parameters if you want
public MyClass(String... params)
and
// I require one parameter, you can pass some additional if you want
public MyClass(String param1, String... otherParams)
If you want do it at compile time you need it to do as you suggested in your last code example.
Then you can use the ApacheCommons - ArrayUtils class:
String[] allParams = ArrayUtils.add(otherParams, 0, param1); //Insert the first param at the first position of the array.
Throw a IllegalArgumentException if the caller did not supply a non-empty parameter array.
EDIT: paraphrased the original text as answer
来源:https://stackoverflow.com/questions/31382106/nice-way-to-force-user-fill-varargs-parameter-in-java