Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a method return Class or Class<?>?

Tags:

java

generics

The Java Guidelines for Wildcard Use says:

Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards.

The Object getClass method returns a Class<?>. The various methods in Class accept a Class<?> and if you pass in a Class the compiler returns an unchecked warning. This leads me to think that always using Class<?> is preferable.

If I have a method which returns a Class, and I don't know how that object will be used, which type should I return Class or Class<?>? Why? Are there any scenarios in which I might want to return simply Class?

like image 619
David V Avatar asked May 06 '14 18:05

David V


2 Answers

Using MyType<?> is always preferable to using a raw MyType (and this extends to Class). The guidelines take it as a given that new code will not use raw types, which are only supported for backwards compatibility. They are not suggesting you abandon generics when ? is the best you can do.

By using the wildcard parameter, the compile-time type safety guarantees of generics still hold. These guarantees only exist in the absence of casts and raw types.

like image 139
Mark Peters Avatar answered Sep 21 '22 23:09

Mark Peters


If you want to return a type that is generic then using a wildcard is definitely preferable to using a raw type - if you start using raw types in your code then that effectively switches off all the other type safety checks you would gain from using generics properly.

The guideline says wildcards should be avoided, not that they must not be used. You should use the most specific type that makes sense in a given scenario, which may be a concrete instantiation of the type parameters, a bounded extends or super wildcard, or an unbounded wildcard, but any of these is a better choice than a raw type.

like image 43
Ian Roberts Avatar answered Sep 24 '22 23:09

Ian Roberts