Cross Compilation in Java 13 and Java 8

1k Views Asked by At

I want to load a Java version specific JavaCompiler.

This is how I take compiler instance currently:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

My aim is to compile a "user Java code" according to the Java version (Java 8 or Java 13) in which it is originally written.

I am building my whole source code in Java 8.

Hence compiler instance that I am getting will be Java 8 specific and I can not compile Java 13 code (correct me if I am wrong).

I have both Java 8 and Java 13 installed.

I read below statement from this article

The ToolProvider locates the default compiler in this case. It is also possible to locate alternative compilers or tools by using service provider mechanism.

Is there any way from which I can load Java version specific Java compiler? Is there a workaround for it?

Or, if I build project using Java 13, can I then compile version-specific using --target or --source or --release arguments of Java 13 compiler?

2

There are 2 best solutions below

0
On

I haven't tried this, but the following snippet might get you going:

JavaCompiler eclipseCompiler = ServiceLoader.load(org.eclipse.jdt.internal.compiler.tool.EclipseCompiler.class).iterator().next();

To build your application you just need to add the following to your depedencies (given as maven coordinates):

<groupId>org.eclipse.jdt</groupId>
<artifactId>ecj</artifactId>
<version>3.21.0</version>

This will run on Java 8 and allows your application to compile for compliance 13.

0
On

So the final approach I used is:

Step 1:

Install both Java 8 and Java 13.

Step 2:

Make Java 13 default

both javac and java

Step 3:

Build the project in Java 13

Step 4:

Use Java 13 compiler to compile both Java 8 and Java 13 programs.

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

It will give you Java 13 compiler.

Step 5:

While compilation I used the --release option.

You have to specify

--release 13 for Java 13 (or u don't have too, as the compiler is Java 13 only)

and

--release 8 for Java 8.

Step 6: For executing the class files:

java 8 execution path for java 8 execution.

for ex:

path_to_java_8/java Helloworld

For Java 13 execution you can directly use java command as java 13 is default

java Helloworld