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

前端 未结 5 1630
失恋的感觉
失恋的感觉 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.

提交回复
热议问题