简体   繁体   中英

Maven compiler source and target

I have searched all the answers on why we should have source different than target but non is convencing:

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
      <source>1.7</source>
      <target>1.8</target>
    </configuration>
  </plugin>

If JDK is backward compatible why do I need to set the target to 1.8 when the compilation is done on 1.7 ?

Setting the source higher than target won't work , example for the error :

Source release 8 requires target release 1.8

Also from Maven :

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

Can anyone give example ? maven source and target are for my own source code not for the dependencies , then what is the case I can use API in later JRE ( in my own code ) compiles successfully ?

Generally one would set the target JVM to match the source JVM, otherwise. If the target JVM is NOT set, the version of the Java compiler will set it to that JVM version, eg If you used Java 10 to build, then the target class files will only run under Java 10 unless you specified target JVM to be something lower.

I guess in the case where your enterprise is targeting a target JVM (eg Java 8 b/c or either security and/or performance reasons) which is higher than what you would like your source Java to be compatible with (eg Java 7), then you would set the target version to be higher than the source. Maybe you might "share" this code library to others that could still be targeting a Java 7 JVM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM