I use java 7, and I create a varargs method
public class JavaApplicationTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
addBundleMessage("b", Integer.SIZE, "key", (Object) null);
}
public static void addBundleMessage(String bundleName, Integer severity, String key, Object... params) {
if (params == null)
System.out.println("params Is null");
else
System.out.println("Params not null");
}
}
If I don’t cast the object, the IDEs Netbeans or Eclipse complains but it compiles :
non-varargs call of varags method with inexact argument type for last
parameter
When No cast : it display params Is null
When I cast null to (Object) it display Params not null
When I cast null to (Object[]) it display params Is null
Is it normal behavior ?
Yes, that is “normal” behaviour.
The confusion comes from varargs being bolted on to the language later and being implemented using an array as the “real parameter” to hold the variable number of parameters.
is almost the same as
and under the hoods, the params are passed wrapped as an Object[].
However, you still have the option to pass in that array yourself.
If you use
(Object[]) null, you get a parameter (that is null).If you use
(Object) null, it uses the varargs method, so it passes in an array to hold the parameters (of which there is only one which is null).For “normal use” of a varargs method,
paramswill never be null. The “worst” you can get is an empty array (if there are no arguments at all).