Requiring at least one element in java variable argument list

The unique way to validate is verifies the params.

Validate the arguments :

if (numbers == null || numbers.length == 0 ) {
            throw new IllegalArgumentException("Your angry message comes here");
        }

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.


I suppose one incredibly hacky way to do this is to create a no-args method and mark it as deprecated. Then compile with these two flags: -Xlint:deprecation -Werror. This will cause any use of a deprecated method to be a compile time error.

edit (a long time after the initial answer):

A less hacky solution would be to ditch the MyClass(Integer... numbers) constructor and replace it with MyClass(Integer[] numbers) (and add a private no-args constructor). It stops the compiler from being able to implicitly use the super class constructor, but without any args, and gives you a compile time error message.

./some_package/Child.java:7: error: constructor Parent in class Parent cannot be applied to given types;
    public Child(Integer[] args) {
                                 ^
  required: Integer[]
  found: no arguments
  reason: actual and formal argument lists differ in length

The cost is your calling syntax will become a bit more verbose:

new Child(new Integer[] {1, 2, 3});

You can of course write a helper functions to help with this eg.

public static Child newInstance(Integer... numbers) {
    return new Child(numbers);
}

@SafeVarargs
public static <T> T[] array(T... items) {
    return items;
}

and then:

Child c0 = Child.newInstance(1, 2, 3);
Child c1 = new Child(array(1, 2, 3));