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

会有一股神秘感。 提交于 2019-11-30 19:38:21

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

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