Why do I get a compilation warning here (var args method call in Java)

前端 未结 5 1615
失恋的感觉
失恋的感觉 2020-12-04 17:29

Source:

public class TestVarArgs {
  public void varArgsMethod(Object ... arr) {
     System.out.println(arr.getClass().getName());
     for(Object o : arr)          


        
相关标签:
5条回答
  • 2020-12-04 18:01

    It is because String[] and Object... do not exactly match up.

    You have to cast the String[] to either Object[] (if you want to pass the Strings as separate parameters) or Object (if you want just one argument that is an array) first.

     tva.varArgsMethod((Object[])args);    // you probably want that
    
     tva.varArgsMethod( (Object) args);    // you probably don't want that, but who knows?
    

    Why is this a warning and not an error? Backwards compatibility. Before the introduction of varargs, you had these methods take a Object[] and code compiled against that should still work the same way after the method has been upgraded to use varargs. The JDK standard library is full of cases like that. For example java.util.Arrays.asList(Object[]) has changed to java.util.Arrays.asList(Object...) in Java5 and all the old code that uses it should still compile and work without modifications.

    0 讨论(0)
  • 2020-12-04 18:04

    Modify the method as

    public void varArgsMethod(String ... arr)
    
    0 讨论(0)
  • 2020-12-04 18:05

    One of the elegant ways to get rid off this warning: instead of tva.varArgsMethod(args) call tva.varArgsMethod(Arrays.stream(args).toArray()) explicitly showing that you pass multiple arguments. Another way to get rid off the warning is to use following call:

    tva.varArgsMethod(Arrays.asList(args).toArray())
    

    Anyway we have to convert the args to Array.

    0 讨论(0)
  • 2020-12-04 18:18

    The argument of type String[] should explicitly be cast to Object[] for the invocation of the varargs method varArgsMethod(Object...) from type TestVarArgs. It could alternatively be cast to Object for a varargs invocation
    You can fix it by doing either one of the way If you cast the String[] to Object[] (ref:tva.varArgsMethod((Object[])args);)
    OR
    change the parameter of method to String[]
    (ref:public void varArgsMethod(String ... paramArr))

    0 讨论(0)
  • 2020-12-04 18:18

    The casts to Object and Object[] did not work out for me, it broke my code, resulting in "Encountered array-valued parameter binding, but was expecting [java.lang.String (n/a)]" and other randomness.

    My line that showed the warning (subj) is the following, where filter.getStates() is of type String[]

    p.add(root.join(DeviceEntity_.state, JoinType.LEFT).get(ClassifierEntity_.CODE).in(filter.getStates()));

    The solution that worked is to use Arrays.asList(filter.getStates()) instead of casting. Good luck!

    0 讨论(0)
提交回复
热议问题