This commit is contained in:
Clément Fournier committed 2024-04-03 18:14:54 +02:00
1 parent fe0b4a9b36
commit 1d18209d11
1 file changed
+43 -6
@@ -1442,15 +1442,52 @@ class Foo{
class="net.sourceforge.pmd.lang.java.rule.bestpractices.UnnecessaryVarargsArrayCreationRule" class="net.sourceforge.pmd.lang.java.rule.bestpractices.UnnecessaryVarargsArrayCreationRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#unnecessaryvarargsarraycreation"> externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#unnecessaryvarargsarraycreation">
<description> <description>
todo Reports explicit array creation when a varargs is expected.
For instance:
```java
Arrays.asList(new String[] { "foo", "bar", });
```
can be replaced by:
```java
Arrays.asList("foo", "bar");
```
This rule also reports such array creations when they are confusing, because the array is a subtype of the component type of the expected array type.
For instance if you have
```java
void varargs(Object... parm);
```
and call it like so
```java
varargs(new String[]{"a"});
```
it is not clear whether you intended the method to receive the value `new Object[]{ new String[] {"a"} }` or just `new String[] {"a"}` (the latter happens). This confusion occurs because `String[]` is both a subtype of `Object[]` and of `Object`. To clarify your intent in this case, use a cast or pass individual elements like so:
```java
// varargs call
// parm will be `new Object[] { "a" }`
varargs("a");
// non-varargs call
// parm will be `new String[] { "a" }`
varargs((Object[]) new String[]{"a"});
// varargs call
// parm will be `new Object[] { new String[] { "a" } }`
varargs((Object) new String[]{"a"});
```
</description> </description>
<priority>3</priority> <priority>3</priority>
<example><![CDATA[ <example><![CDATA[
class C { import java.util.Arrays;
// todo
} class C {
]]> static {
</example> Arrays.asList(new String[]{"foo", "bar",});
// should be
Arrays.asList("foo", "bar");
}
}
]]></example>
</rule> </rule>