diff --git a/pmd-java/src/main/resources/category/java/bestpractices.xml b/pmd-java/src/main/resources/category/java/bestpractices.xml index 85840d7e2e..ef111645a0 100644 --- a/pmd-java/src/main/resources/category/java/bestpractices.xml +++ b/pmd-java/src/main/resources/category/java/bestpractices.xml @@ -1442,15 +1442,52 @@ class Foo{ class="net.sourceforge.pmd.lang.java.rule.bestpractices.UnnecessaryVarargsArrayCreationRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#unnecessaryvarargsarraycreation"> - 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"}); + ``` 3 - +import java.util.Arrays; + +class C { + static { + Arrays.asList(new String[]{"foo", "bar",}); + // should be + Arrays.asList("foo", "bar"); + } +} + ]]>