In this code construct:
public MyClass(Integer... numbers) { do_something_with(numbers[]); }
is it possible to require that numbers
contains at least one entry in such a way, that this is checked at compile-time? (At run-time, of course, I can just check numbers.length.)
Clearly I could do this:
public MyClass(Integer number, Integer... more_numbers) { do_something_with(number, more_numbers[]); }
but this isn't going to be very elegant.
The reason I would like to do this is to make sure that a sub-class does not simply forget to call this constructor at all, which will default to a call to super()
with no numbers in the list. In this case, I would rather like to get the familiar error message: Implicit super constructor is undefined. Must explicitly invoke another constructor
.
Could there be another way to achieve the same, like some @-annotation that marks this constructor as non-implicit?
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.
13) How many maximum numbers of Varargs or Variable-Arguments can be there in a method or a constructor in Java? Explanation: Yes, only one.
I think the best approach to have at least 1 argument is to add one like this:
public MyClass (int num, int... nums) { //Handle num and nums separately int total = num; for(i=0;i<nums.length;i++) { total += nums[i]; } //... }
Adding an argument of the same type along with varargs will force the constructor to require it (at least one argument). You then just need to handle your first argument separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With