Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile with Java 11 target Java 1.8 in IntelliJ

I am trying to compile with JDK 11 but target Java 1.8 in IntelliJ. I have configured:

  • Project Settings:
    • Project SDK: 11
    • Project language level: 8
  • Java Compiler Settings:
    • Use '--release' option for cross-compilation (Java 9 and later)
    • Project bytecode version: 8
  • Module Settings:
    • Project SDK (11)
    • Language level: Project default (8 - Lambdas, type annotations etc.)

I get a bunch of compilation errors saying that internal packages do not exist. --add-exports is not valid with --target 1.8 so that doesn't help.

The only thing that does work is to set the Project SDK back to Java 1.8 (which causes other problems when trying to run with Java 11 but that is another issue).

Is it possible to compile with JDK 11 and target Java 1.8 in IntelliJ?

There are other related questions which seem to work but not from IntelliJ:

  • How to produce code in Java 11, but target Java 8 and above?
  • Move to OpenJDK-11 but compile in Java 8
like image 500
steinybot Avatar asked Apr 10 '19 00:04

steinybot


People also ask

Can we compile Java 8 code with Java 11?

The class files created by Java 8 are still executable in Java 11; however, there have been other changes in the Java runtime (library changes, etc.) that might require modification of the code. These modifications may be made in Java 8 and compiled with Java 8 making it compatible with the Java 11 runtime.

Is Java 1.8 the same as Java 8?

javac -source 1.8 (is an alias for javac -source 8 ) java.


1 Answers

Unfortunately, you can't use internal APIs if you compile with the --release N option. This is described in JEP 247:

A new command-line option, --release, is defined, which automatically configures the compiler to produce class files that will link against an implementation of the given platform version. --release N is roughly equivalent to:

for N < 9: -source N -target N -bootclasspath <documented-APIs-from-N>,

for N >= 9: -source N -target N --system <documented-APIs-from-N>.

And then follows the main paragraph:

For N < 9, the documented APIs consist of the public APIs that were on javac's default bootclasspath for JDK N.

I agree this is a big limitation actually. You can't even use sun.misc.Unsafe which has always been a critical part of OpenJDK.

So, your question has nothing to do with IntelliJ IDEA. It's a limitation of the Java platform.

You have two ways:

  • Don't use internal APIs
  • Use JDK 8 for compilation
like image 72
ZhekaKozlov Avatar answered Oct 14 '22 03:10

ZhekaKozlov