Files
openide/java/java-impl/resources/inspectionDescriptions/BoundedWildcard.html
Leonid Shalupov 40795fe787 IJI-2422: community/java: move resources under resources root
GitOrigin-RevId: 8b2b63fc6db476ca0c2cfe5cadd84db6c4236d0f
2025-02-05 04:43:28 +00:00

72 lines
2.6 KiB
HTML

<html>
<body>
Reports generic method parameters that can make use of <a href="https://en.wikipedia.org/wiki/Wildcard_(Java)">bounded wildcards</a>.
<p><b>Example:</b></p>
<pre><code>
void process(Consumer&lt;Number&gt; consumer);
</code></pre>
<p>should be replaced with:</p>
<pre><code>
void process(Consumer&lt;? super Number&gt; consumer);
</code></pre>
<p>
This method signature is more flexible because it accepts more types: not only
<code>Consumer&lt;Number&gt;</code>, but also <code>Consumer&lt;Object&gt;</code>.
</p>
<p>Likewise, type parameters in covariant position:</p>
<pre><code>
T produce(Producer&lt;T&gt; p);
</code></pre>
<p>should be replaced with:</p>
<pre><code>
T produce(Producer&lt;? extends T&gt; p);
</code></pre>
<!-- tooltip end -->
<p>
To quote <a href="https://en.wikipedia.org/wiki/Joshua_Bloch#Effective_Java">Joshua Bloch</a> in <em>Effective Java</em> third Edition:
</p>
<blockquote>
<h4>Item 31: Use bounded wildcards to increase API flexibility</h4>
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.
</blockquote>
<p>
Use the inspection options to toggle the reporting for:
</p>
<ul>
<li>
<p>
invariant classes. An example of an invariant class is <code>java.util.List&lt;T&gt;</code> because it both accepts values
(via the <code>List.add(T)</code> method)
and produces values (via the <code>T List.get()</code> method).
</p>
<p>
On the
other hand, <code>contravariant</code> classes only receive values, for example, <code>java.util.function.Consumer&lt;T&gt;</code>
with the only method <code>accept(T)</code>. Similarly, <code>covariant</code> classes
only produce values, for example, <code>java.util.function.Supplier&lt;T&gt;</code>
with the only method <code>T get()</code>.
</p>
<p>
People often use bounded wildcards in covariant/contravariant
classes but avoid wildcards in invariant classes, for example, <code>void process(List&lt;? extends T&gt; l)</code>.
Disable this option to ignore such invariant classes and leave them rigidly typed, for example, <code>void
process(List&lt;T&gt; l)</code>.
</p>
</li>
<li>
<p>
<code>private</code> methods, which can be considered as not a part of the public API
</p>
</li>
<li>
<p>
instance methods
</p>
</li>
</ul>
</body>
</html>