Can a vararg parameter be of type <? super Object>?

Question

I'm writing a method to check if parameters of my methods are null, and I was just opened up to the idea of varargs, so I wrote a cool catch-all method:

private <T> void checksIfNull(T... t) throws NullPointerException {
    for (T myT : t) {
        if ( myT == null) {
            throw new NullPointerException("Attempted to pass a null object");
        }
    }
}

But I'm getting greedy. If I need to check a String, List, and int, all in one meeting, it means I have to write this in the calling method:

checksIfNull(myString);
checksIfNull(myList);
checksIfNull(myInt);

I'm wondering if there's a way that I would only every have to call the null-checking method once using combined with a generic parameter. I feel there might be - but I may have the syntax wrong. I've tried some combinations of the following but it never quite works out:

private <T> void checksIfNull(T<? super Object>... t) throws NullPointerException {
    for (T myT : t) {
        if ( myT == null) {
            throw new NullPointerException("Attempted to pass a null object");
        }
    }
}

My right hand parameter of T<? super Object>... t is telling me "Type T does not have type parameters.


Show source
| generics   | java   | varargs   2017-01-07 05:01 1 Answers

Answers ( 1 )

  1. 2017-01-07 05:01

    Generics aren't adding any value here. Having T... t implies there's some commonality among the types of the parameters, something you're trying to avoid. You can simply use Object....

    private void checksIfNull(Object... values) throws NullPointerException {
        for (Object value: values) {
            if (value == null) {
                throw new NullPointerException("Attempted to pass a null object");
            }
        }
    }
    
◀ Go back