vararg参数的类型是否为<! - ?超级对象 - >?

时间:2017-01-07 04:38:19

标签: java generics variadic-functions

我正在编写一个方法来检查我的方法的参数是否为空,并且我刚刚接受了varargs的想法,所以我写了一个很酷的catch-all方法:

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

但我变得贪婪。如果我需要在一次会议中检查StringListint,则表示我必须在调用方法中写入此内容:

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

我想知道是否有一种方法,我只需要使用与通用参数结合使用时调用null检查方法。我觉得可能有 - 但我可能有错误的语法。我尝试了以下几种组合,但它从未完全解决:

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");
        }
    }
}

T<? super Object>... t的右手参数告诉我&#34; Type T没有类型参数。

1 个答案:

答案 0 :(得分:3)

泛型不是在这里添加任何值。让T... t暗示参数类型之间存在一些共性,这是您试图避免的。您只需使用Object...

即可
private void checksIfNull(Object... values) throws NullPointerException {
    for (Object value: values) {
        if (value == null) {
            throw new NullPointerException("Attempted to pass a null object");
        }
    }
}
相关问题