简体   繁体   English

定义异常类列表-类型不匹配错误

[英]defining a list of exception classes - Type mismatch error

i am trying to define a list of exception classes like so: 我试图定义一个异常类的列表,像这样:

private static final List<Class<? extends Exception>> SOME_ERRORS = Arrays.asList(NumberFormatException.class, NullPointerException.class);

the error i get from Eclipse is this: 我从Eclipse中得到的错误是:

Type mismatch: cannot convert from List<Class<? extends RuntimeException>> to List<Class<? extends Exception>>

Could you please advise? 您能否提一些建议? I don't see why it can't convert a list of Exceptions to a list of Exceptions... 我不明白为什么它不能将例外列表转换为例外列表...

You should use: 您应该使用:

List<Class<? extends RuntimeException>> SOME_ERRORS = Arrays.asList(NumberFormatException.class, NullPointerException.class);

The generics type returned from Arrays.asList will always use the most specific type, ie RuntimeException . Arrays.asList返回的泛型类型将始终使用最特定的类型,即RuntimeException If you added a checked exception to the list, this statement would become: 如果将已检查的异常添加到列表中,则该语句将变为:

List<Class<? extends Exception>> SOME_ERRORS = Arrays.asList(IOException.class, NumberFormatException.class, NullPointerException.class);

+1 for Reimeus's answer . +1为Reimeus的答案 However, if you'd prefer to keep the list declared using the parent Exception type, this is the best I can come up with (using Java 7 syntax): 但是,如果您希望保留使用父Exception类型声明的列表,那么这是我能想到的最好的方法(使用Java 7语法):

private static final List<Class<? extends Exception>> SOME_ERRORS = new ArrayList<>();
static{
    SOME_ERRORS.add(NumberFormatException.class);
    SOME_ERRORS.add(NullPointerException.class);
}

Your issue is due to Arrays.asList automatically determining the proper list type for you. 您的问题是由于Arrays.asList自动为您确定正确的列表类型。 To compare, this also works without error: 进行比较,这也可以正常工作:

private static final List<Class<? extends Exception>> SOME_ERRORS = Arrays.asList(NumberFormatException.class, NullPointerException.class, Exception.class);

Especially dealing with "constants" ( static final s), you're usually best advised to ensure that such arrays / collections can't be modified. 尤其是处理“常量”( static final )时,通常最好建议您确保不能修改此类数组/集合。 At worst, this can save running into some difficult issues. 最坏的情况是,这样可以避免遇到一些难题。 For example: 例如:

private static final List<Class<? extends Exception>> SOME_ERRORS;
static{
    List<Class< ? extends Exception>> errors = new ArrayList<>();
    errors.add(NumberFormatException.class);
    errors.add(NullPointerException.class);

    SOME_ERRORS = Collections.unmodifiableList(errors);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM