为什么我在这里得到一个编译警告(用Java中的var args方法调用) [英] Why do I get a compilation warning here (var args method call in Java)

查看:150
本文介绍了为什么我在这里得到一个编译警告(用Java中的var args方法调用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来源:

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

  public static void main(String[] args) {
    TestVarArgs tva = new TestVarArgs();
    tva.varArgsMethod(args);    
  }
}

编译:

javac TestVarArgs.java 

错误:

TestVarArgs.java:15: warning: non-varargs call of varargs method with inexact argument type for last parameter;
cast to java.lang.Object for a varargs call
cast to java.lang.Object[] for a non-varargs call and to suppress this warning    
tva.varArgsMethod(args);     
^

1 warning

我使用 javac 1.6.0_20 并且代码o / p表示无论如何都进行了非var arg调用。

I am using javac 1.6.0_20 and the code o/p indicates that a non var arg call was made anyways.

推荐答案

这是因为 String [] 对象... 不完全匹配。

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

你必须将 String [] 强制转换为 Object [] (如果你想将字符串作为单独的参数传递)或对象(如果你只想要一个参数是一个数组)。

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?

为什么这是警告而不是错误?向后兼容性。在引入varargs之前,你有这些方法采用 Object [] ,并且在该方法升级为使用varargs之后,编译的代码仍应以相同的方式工作。 JDK标准库充满了这样的案例。例如 java.util.Arrays.asList(Object [])已更改为 java.util.Arrays.asList(Object ...)< Java5中的/ code>以及使用它的所有旧代码仍然可以编译和工作而无需修改。

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.

这篇关于为什么我在这里得到一个编译警告(用Java中的var args方法调用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆