为什么javac“-source”标志不起作用?

时间:2012-08-03 10:57:03

标签: java javac

我正在测试javac -source标志,我对它应该如何工作有点困惑。

以此代码为例。它是一个不兼容的Java5代码,因为在该版本的JDK中没有为String定义方法isEmpty()

public class TestJavac {
   public static void Main(String args[]) {
   String pippo = "pippo";   
   pippo.isEmpty();
   }
}

尝试使用以下编译:

javac -source 5 TestJavac.java

然后它的作品! 这对我来说听起来很奇怪,但也许有些东西我无视。 我的JAVA_HOME指向1.6 JDK

3 个答案:

答案 0 :(得分:5)

source选项仅适用于语言级别,不适用于API(由JDK运行时库提供)。

有一个单独的选项(-bootclasspath -extdirs)来指定要使用的JDK(并且需要获取相应的jar文件)。

请注意,还有-target(控制输出字节码版本)。

你应该总是指定所有(或者甚至使用较旧的JDK编译,你或多或少需要第二个开关才能工作)

答案 1 :(得分:2)

源标志仅用于验证语言功能,来自-source标志的文档:

1.3  The compiler does not support assertions, generics, or other
     language features introduced after Java SE 1.3.

1.4  The compiler accepts code containing assertions, which were 
     introduced in Java SE 1.4.

1.5  The compiler accepts code containing generics and other language 
     features introduced in Java SE 5.

5    Synonym for 1.5.

1.6  No language changes were introduced in Java SE 6. However, encoding 
     errors in source files are now reported as errors instead of warnings 
     as in previous releases of Java SE.

6    Synonym for 1.6.

1.7  This is the default value. The compiler accepts code with features 
     introduced in Java SE 7.

如您所见,java 6中没有引入任何更改。

答案 2 :(得分:1)

-source仅检查java语法,而不是包含的库。例如它忽略了@since 1.6 :(

类似地,-target将生成将在旧版本的JVM上加载但可能无法运行的类。

http://vanillajava.blogspot.co.uk/2012/02/using-java-7-to-target-much-older-jvms.html