Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top