Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics: creating collections of class objects extending Throwable

Tags:

java

generics

Why does the first line work, but the second one doesn't?

Collection<Class<? extends Throwable>> exs =
    new ArrayList<Class<? extends Throwable>>() {{ add(MyOwnException.class); }};
Collection<Class<? extends Throwable>> exs = Arrays.asList(MyOwnException.class);
like image 572
Andres Riofrio Avatar asked Sep 19 '12 23:09

Andres Riofrio


People also ask

Can we create generic exception by extending throwable class?

Core Java bootcamp program with Hands on practiceA generic class is not allowed to extend the Throwable class directly or indirectly. A method is not allowed to catch an instance of a type parameter.

What Cannot be parameterized with a type using generics?

Correct Option: C. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.

What is <? Super T in Java?

super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .


1 Answers

The reason it's an error is that java is inferring the wrong type, but you can make it compile, without casting, by specifying the type in the call to the typed method Arrays.asList():

Collection<Class<? extends Throwable>> exs 
    = Arrays.<Class<? extends Throwable>>asList(Exception.class); // compiles

Without specifying the type, java infers the element type of the collection to be Class<Exception>, which is not assignable to Collection<Class<? extends Throwable>>.

Remember with generics that if B extends A, List<B> does not extend List<A>.

like image 194
Bohemian Avatar answered Oct 02 '22 21:10

Bohemian