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?
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.