Why javac target option can not be lower than source option?
Asked Answered
T

1

5

I have read about source and target options for javac that they define a version that my source code requires to compile and oldest JRE version i want to support, respectively. While using Maven build tool i have defined these parameters in pom.xml like this:

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

, but target version can not be set lower than source version, why is it so?

Trying to compile with this configuration results in error: "Fatal error compiling: warning: source release 15 requires target release 15". Same with any other combination of source version being higher than target.

Triolein answered 21/1, 2021 at 22:21 Comment(2)
New language features often require support by the JVM to be implemented. A good example is that lambdas require invokedynamic. Therefore targeting a JVM version earlier than the one that got those features added would break: you'd produce bytecode that the target JVM can't interpret. There is a workaround, that's called "retrocompiling", but it's not offered by javac itself, but some third party tools can do it.Apace
@JoachimSauer did you just make up the "retrocompiling" wordChristal
L
6

Because that is how it is designed. From the documentation of javac in Java SE 15 for the --target option:

Note: The target release must be equal to or higher than the source release. (See --source.)

I guess the usual is to have old source code that you want to run in newer releases and, when starting a project, you choose your source release as the oldest release that you want to support.

Look at this answer for a discussion about backward and forward compatibility:

In brief, we can say:

  • JDK's are (usually) forward compatible.
  • JRE's are (usually) backward compatible.

You can think about it as this: JDKs can compile (usually) for newer releases and JREs can run (usually) older releases.

Loosing answered 22/1, 2021 at 0:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.