rspec/rules/S5669/java/rule.adoc

42 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Passing single ``++null++`` or primitive array argument to the variable arity method may not work as expected. In the case of ``++null++``, it is not passed as array with single element, but the argument itself is ``++null++``. In the case of a primitive array, if the formal parameter is ``++Object...++``, it is passed as a single element array. This may not be obvious to someone not familiar with such corner cases, and it is probably better to avoid such ambiguities by explicitly casting the argument to the desired type.
== Noncompliant Code Example
----
class A {
public static void main(String[] args) {
vararg(null); // Noncompliant, prints "null"
int[] arr = {1,2,3};
vararg(arr); // Noncompliant, prints "length: 1"
}
static void vararg(Object... s) {
if (s == null) {
System.out.println("null");
} else {
System.out.println("length: " + s.length);
}
}
}
----
== Compliant Solution
----
class A {
public static void main(String[] args) {
vararg((Object) null); // prints 1
Object[] arr = {1,2,3};
vararg(arr); // prints 3
}
static void vararg(Object... s) {
if (s == null) {
System.out.println("null"); // not reached
} else {
System.out.println("length: " + s.length);
}
}
}
----