Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
The Java compiler type-checks the arguments to a varargs method to ensure that they are of the same type or object reference. However, the compile-time checking is ineffective when two method signatures are used in particular - {{Object}} and the generic type {{T}} \[[Bloch 08|AA. Java References#Bloch 08]\]. 

Another requirement for providing A variable arity (aka varargs) method is a method that can take a variable number of arguments. The method must contain at least one fixed argument. When processing a variable arity method call, the Java compiler checks the types of all arguments, and all of the variable actual arguments must match the variable formal argument type. However, compile-time type checking is ineffective when Object or generic parameter types are used [Bloch 2008]. The presence of initial parameters of specific types is irrelevant; the compiler will remain unable to check Object or generic variable parameter types. Enable strong compile-time type checking of variable argument methods is to be as specific as possible when declaring the type of the arity methods by using the most specific type possible for the method parameter.

Noncompliant Code Example (Object)

This noncompliant code example declares two methods, one with an Object parameter and another with a generic type T. Both these approaches are flawed as they break string compile-time type checkingsums a set of numbers using a variable arity method that uses Object as the variable arity type. Consequently, this method accepts an arbitrary mix of parameters of any object type. Legitimate uses of such declarations are rare (but see the "Applicability" section of this guideline).

Code Block
bgColor#FFCCCC

ReturnType1double suspect1sum(Object... args) {
   double result = 0.0;
   for (Object arg : args) {
     if (arg instanceof Byte) {
       result += ((Byte) arg).byteValue();
     } else if (arg instanceof Short) {
       result += ((Short) arg).shortValue();
     }
<T> ReturnType2 suspect2(T... args) { }

Compliant Solution

 else if (arg instanceof Integer) {
       result += ((Integer) arg).intValue();
     } else if (arg instanceof Long) {
       result += ((Long) arg).longValue();
     } else if (arg instanceof Float) {
       result += ((Float) arg).floatValue();
     } else if (arg instanceof Double) {
       result += ((Double) arg).doubleValue();
     } else {
       throw new ClassCastException();
     }
   }
   return result;
}

Compliant Solution (Number)

This compliant solution defines the same method but uses the Number type. This abstract class is general enough to encompass all numeric types, yet specific enough to exclude nonnumeric Do not use generic types like Object in varargs and be as specific as possible when declaring parameter types.

Code Block
bgColor#ccccff

ReturnType1double specific1sum(primitiveType1Number... args) { }
ReturnType2 specific2(primitiveType2
  // ... args) { }

}

Noncompliant Code Example (Generic Type)

This noncompliant code example shows autoboxing in action when the doSomething method is called with the primitive integer 1 as a parameter (converted to Integer type)declares the same variable arity method using a generic type parameter. It accepts a variable number of parameters that are all of the same object type; however, it may be any object type. Again, legitimate uses of such declarations are rare.

Code Block
bgColor#FFCCCC

doSomething(1)

private void doSomething(Integer<T> double sum(T... iargs) {
  System// ..out.println("autoboxed");
}

Compliant Solution

...

(Generic Type)

This compliant solution defines the same generic method using the Number typeBe as specific as possible while defining the type of a varargs method to enforce strong compile-time checking.

Code Block
bgColor#ccccff

doSomething(1)

private void doSomething(int<T extends Number> double sum(T... iargs) {
  // use int instead of Integer here
  System.out.println("specific");
}

Wiki Markup
Retrofitting old methods containing {{final}} array parameters with generically typed varargs is not always a good idea. This is because if some method did not accept an argument of a particular type, it may be possible to override the compile-time checking so that with the use of generic varargs, it now compiles cleanly. \[[Bloch 08|AA. Java References#Bloch 08]\]

Risk Assessment

...
}

Be as specific as possible when declaring parameter types; avoid Object and imprecise generic types in variable arity methods. Retrofitting old methods containing final array parameters with generically typed variable arity parameters is not always a good idea. For example, given a method that does not accept an argument of a particular type, it could be possible to override the compile-time checking—through the use of generic variable arity parameters—so that the method would compile cleanly rather than correctly, causing a runtime error [Bloch 2008].

Also, note that autoboxing prevents strong compile-time type checking of primitive types and their corresponding wrapper classes. For instance, this compliant solution produces the following warning but works as expected:

Java.java:10: warning: [unchecked] Possible heap pollution from parameterized vararg type T
<T extends Number> double sum(T... args) {

Applicability

Injudicious use of variable arity parameter types prevents Unmindful use of the varargs feature breaks strong compile-time type checking, may create creates ambiguity, and diminish diminishes code readability.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL08-J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Sun 06|AA. Java References#Sun 06]\] [varargs|http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html] 
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 42: "Use varargs judiciously"
\[[Steinberg 05|AA. Java References#Steinberg 05]\] "Using the Varargs Language Feature"

Variable arity signatures using Object and imprecise generic types are acceptable when the body of the method lacks both casts and autoboxing and it also compiles without error. Consider the following example, which operates correctly for all object types and type-checks successfully:

Code Block
bgColor#ccccff
<T> Collection<T> assembleCollection(T... args) {
  return new HashSet<T>(Arrays.asList( args));
}

In some circumstances, it is necessary to use a variable arity parameter of type Object.  A good example is the method java.util.Formatter.format(String format, Object... args), which can format objects of any type.

Automated detection is straightforward.

Bibliography

[Bloch 2008]

Item 42, "Use Varargs Judiciously"

[Steinberg 2008]

"Using the Varargs Language Feature"

[Oracle 2011b]

Varargs

 

...

Image Added Image Added Image AddedDCL07-J. Ensure failure atomicity by declaring class and instance variables final and initializing immediately      01. Declarations and Initialization (DCL)      01. Declarations and Initialization (DCL)