Nice way to force user fill varargs parameter in Java [duplicate]

爷,独闯天下 提交于 2019-11-30 03:48:59

问题


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.


回答1:


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");
}



回答2:


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)



回答3:


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.



回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!