| Wiki Markup |
|---|
The Java compiler type- checks the arguments to each varargs method to ensure that the arguments are of the same type or object reference. However, the compile-time checking is ineffective when {{Object}} or generic {{T}} parameter types are used \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. Another requirement for providing strong compile-time type checking of variable argument methods is to be as specific as possible when declaring the type of the method parameter. |
...
| Code Block | ||
|---|---|---|
| ||
ReturnType function(Object... args) { }
|
Noncompliant Code Example (
...
Generic Type)
This noncompliant code example declares a vararg method using a generic type parameter. It accepts a variable number of parameters that are all of the same object type. Again, legitimate uses of such declarations are rare.
...
| Wiki Markup |
|---|
Retrofitting old methods containing final array parameters with generically-typed varargs 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 varargs parameters --- so that the method would compile cleanly rather than correctly, causing a compile-time error \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
Also, note that autoboxing does not allow strong compile-time type checking of primitive types and their corresponding wrapper classes.
...
DCL09-EX1: Varargs signatures using Object and imprecise generic types are acceptable when the body of the method both uses no does not use casts or auto-boxing , and also compiles without error. Consider the following example, which operates correctly for all object types and type - checks successfully.
| Code Block | ||
|---|---|---|
| ||
Collection<T> assembleCollection(T... args) {
Collection<T> result = new HashSet<T>();
// add each argument to the result collection
return result;
}
|
...
Automated detection appears to be straightforward.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
| Wiki Markup |
|---|
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 42: "Use varargsVarargs judiciouslyJudiciously" \[[Steinberg 2005|AA. Bibliography#Steinberg 05]\] "Using the Varargs Language Feature" \[[Sun 2006|AA. Bibliography#Sun 06]\] [varargs|http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html] |
...