我已经使用 Eclipse 多年了,但我从来没有想到过这一点。我的系统上安装了 JDK7,并将其用作工作区 JRE。但是,当我在 maven 项目中包含以下定义时,库部分将 java 库显示为 [JavaSE 1.6],如下图所示。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
我理解源配置和目标配置的概念。但是,我只是不理解 JDK7 库充当 JRE6 的方式(或者是吗?)。谁能解释一下吗?
我使用 Eclipse Mars 和 JDK 1.7 作为工作台 JRE
最佳答案
将配置设置为比您用于构建的 JRE 旧的 JRE 时,无法防止使用错误的 API。
来自manual
Note: Merely setting the target option does not guarantee that your code actually runs on a JRE with the specified version. The pitfall is unintended usage of APIs that only exist in later JREs which would make your code fail at runtime with a linkage error. To avoid this issue, you can either configure the compiler's boot classpath to match the target JRE or use the Animal Sniffer Maven Plugin to verify your code doesn't use unintended APIs.
但是回答你的问题:
But, I'm just not understanding the way JDK7 libraries acts as JRE6. Could anyone explain?
事实并非如此,至少不是。例如,如果您(仅)安装了 JRE 8,但将项目设置为 JRE 7,您可以编写这行代码而不会出现编译错误,因为它是合法的 JRE 7 Java,只需使用 JRE 8 运行时中添加的方法 (join
)。
String join = String.join("", "a", "b");
当您使用 JRE 7 运行它时,您将在运行时得到以下信息:
Exception in thread "main" java.lang.NoSuchMethodError: java.lang.String.join(Ljava/lang/CharSequence;[Ljava/lang/CharSequence;)Ljava/lang/String;
at snippet.Snippet.main(Snippet.java:5)
因此,如果您确实想确保合规性,请使用系统上安装的正确 JRE 进行构建和开发。
关于java - eclipse中JRE系统库的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35477702/