This is my sample code where i am getting the warning.
String lsSQL = foMetaQuery.getSQL();
String lsNewSQL = replace(lsSQL,"'' {","''{");
lsNewSQL = replace(lsNewSQL," } ''","}''");
lsNewSQL = replace(lsNewSQL," }","}");
lsNewSQL = MessageFormat.format(lsNewSQL,foSubstitutionArray);
loVSQueryDef.setSQL(lsNewSQL);
The compiler says
cast to java.lang.Object for a varargs call cast to java.lang.Object[] for a non-varargs call and to suppress this warning
lsNewSQL = MessageFormat.format(lsNewSQL,foSubstitutionArray);
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.
Each method can only have one varargs parameter. The varargs argument must be the last parameter.
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values.
Rules to follow while using varargs in JavaWe can have only one variable argument per method. If you try to use more than one variable arguments a compile time error is generated.
You don't show what type foSubstitutionArray
has, but I'll assume it's an array of a type other than Object.
Now, MessageFormat.Format()
is a varargs method, which means that you can pass it any number of arguments (well, at least 1) and Java will internally collect them all in an array of objects. However, here you're passing in an array, so Java gets confused: are you trying to pass a single argument (that just happens to be an array), or are you passing in the variable arguments?
If you intend to pass a single argument (unlikely), add a cast to Object:
MessageFormat.format(lsNewSql, (Object) foSubstitutionArray)
If you intend values to be taken from your array, cast to Object[]:
MessageFormat.format(lsNewSql, (Object[]) foSubstitutionArray)
MessageFormat.format()
has a variable-arity signature that is a convenience for the programmer, that allows one to write
format("Hello")
format("Hello {0}", name)
format("Hello {0} {1}", first, last)
At the bytecode level, the method signature has two parameters of type String
and Object[]
, but behind the scenes the compiler creates the array for you, so you don't have to type new Object[] {first, last}
. You can still create the array explicitely with format("Hello", new Object[]{})
, and the compiler will be happy.
However when you pass an array of strings as the last parameter, there are two possible interpretations:
format("Hello", new String[] {first, last})
format("Hello", new Object[]{new String[] {first, last}})
For backward compatibility, the compiler assumes the former and issues a warning instead of an error, but it still asks you to insert a cast to either Object
or Object[]
to state in the source code what you really mean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With