java - eclipse中JRE系统库的概念

标签 java eclipse maven

我已经使用 Eclipse 多年了,但我从来没有想到过这一点。我的系统上安装了 JDK7,并将其用作工作区 JRE。但是,当我在 maven 项目中包含以下定义时,库部分将 java 库显示为 [JavaSE 1.6],如下图所示。

enter image description here

<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/

相关文章:

java - 声明了自定义 setter ,但 lombok 似乎没有发生任何事情

java - 将复选框发送到另一个 Activity

java - 不同项目的共享测试资源

java - Maven Archetype 上的 charsetName 引起的 MojoFailureException

java - 从 JNI/NDK 将二维原始数组从 C 返回到 Java

java - 动态改变方法的返回类型

android - 在 Galaxy Tab 中自动连接到 Debug模式

java - import org.appfuse.webapp.action.BaseAction 无法解析

maven - SBT 可以仅将 .pom 文件解析为没有 jar 的依赖项吗?

Java 1.7,APMHAL,向 CLI 发送多参数命令