Back to Intellij Community

BoundedWildcard

java/java-impl/resources/inspectionDescriptions/BoundedWildcard.html

2025.3-rc-21.4 KB
Original Source

Reports generic method parameters that can make use of bounded wildcards.

Example:

void process(Consumer<Number> consumer);

should be replaced with:

void process(Consumer<? super Number> consumer);

This method signature is more flexible because it accepts more types: not only Consumer<Number>, but also Consumer<Object>.

Likewise, type parameters in covariant position:

T produce(Producer<T> p);

should be replaced with:

T produce(Producer<? extends T> p);

To quote Joshua Bloch in Effective Java third Edition:

Item 31: Use bounded wildcards to increase API flexibility

Using wildcard types in your APIs, while tricky, makes the APIs far more flexible. If you write a library that will be widely used, the proper use of wildcard types should be considered mandatory. Remember the basic rule: producer-extends, consumer-super (PECS). Also remember that all Comparables and Comparators are consumers.

Use the inspection options to toggle the reporting for:

  • invariant classes. An example of an invariant class is java.util.List<T> because it both accepts values (via the List.add(T) method) and produces values (via the T List.get() method).

  • private methods, which can be considered as not a part of the public API

  • instance methods