mirror of
https://gitflic.ru/project/openide/openide.git
synced 2025-12-16 22:51:17 +07:00
72 lines
2.6 KiB
HTML
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<Number> consumer);
|
|
</code></pre>
|
|
<p>should be replaced with:</p>
|
|
<pre><code>
|
|
void process(Consumer<? super Number> consumer);
|
|
</code></pre>
|
|
<p>
|
|
This method signature is more flexible because it accepts more types: not only
|
|
<code>Consumer<Number></code>, but also <code>Consumer<Object></code>.
|
|
</p>
|
|
<p>Likewise, type parameters in covariant position:</p>
|
|
<pre><code>
|
|
T produce(Producer<T> p);
|
|
</code></pre>
|
|
<p>should be replaced with:</p>
|
|
<pre><code>
|
|
T produce(Producer<? extends T> 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<T></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<T></code>
|
|
with the only method <code>accept(T)</code>. Similarly, <code>covariant</code> classes
|
|
only produce values, for example, <code>java.util.function.Supplier<T></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<? extends T> l)</code>.
|
|
Disable this option to ignore such invariant classes and leave them rigidly typed, for example, <code>void
|
|
process(List<T> 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> |