【问题标题】:Why javac target option can not be lower than source option?为什么 javac 目标选项不能低于源选项?
【发布时间】:2021-01-21 22:21:54
【问题描述】:

我已经阅读了关于javac 的source 和target 选项,它们分别定义了我的源代码编译所需的版本和我想要支持的最旧的JRE 版本。在使用 Maven 构建工具时,我在 pom.xml 中定义了这些参数,如下所示:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>15</source>
                <target>11</target>
            </configuration>
        </plugin>
    </plugins>
</build>

,但是目标版本不能设置低于源版本,为什么会这样?

尝试使用此配置进行编译会导致错误:“致命错误编译:警告:源版本 15 需要目标版本 15”。与源版本高于目标的任何其他组合相同。

【问题讨论】:

    标签: java maven javac


    【解决方案1】:

    因为它就是这样设计的。来自the documentation of javac in Java SE 15 for the --target option:

    注意:目标版本必须等于或高于源版本。 (见--source。)

    我想通常的做法是让旧的源代码在较新的版本中运行,并且在开始项目时,选择源版本作为要支持的最旧版本。

    查看this answer,了解有关向后和向前兼容性的讨论:

    简而言之,我们可以说:

    • JDK 是(通常)向前兼容的。
    • JRE(通常)向后兼容。

    您可以这样想:JDK(通常)可以为较新的版本编译,而 JRE(通常)可以运行较旧的版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2014-02-16
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2020-10-18
      相关资源
      最近更新 更多