Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is varargs (Class<? extends Throwable>... t) "unchecked or unsafe" operation?

Ok so I'm calling a method with a signature (Class<? extends Throwable>... exceptions) and I get a "File.java uses unchecked or unsafe operations" warning here in the main method:

public class VarargsFun {
    public void onException(Class<? extends Throwable>... exceptions) { }

    public static void main(String[] args) {
        new VarargsFun().onException(IllegalArgumentException.class);
    }
}

Shouldn't the compiler be able to see that IllegalArgumentException does indeed extend RuntimeException, Exception and Throwable?

How should I properly amend my code to get rid of this warning?

I don't really feel like instantiating my exceptions... it seems nicer to use the .class

(dont want to use @SuppressWarnings either!)

Am using java 7. Thanks for any tips.

like image 879
vikingsteve Avatar asked Feb 27 '13 14:02

vikingsteve


1 Answers

It's easiest to understand if you realize that

new VarargsFun().onException(IllegalArgumentException.class);

is just syntactic sugar for

new VarargsFun().onException(
    new Class<? extends Throwable>[]{ IllegalArgumentException.class });

i.e. the call site creates an array with the component type equal to the type of the varargs.

But of course, new Class<? extends Throwable>[] is not allowed in Java. So the compiler does new Class<?>[] instead and gives a warning.

like image 149
newacct Avatar answered Oct 02 '22 20:10

newacct