How to remove --enable-preview in Java 16?

4.8k views Asked by At

To use records with JDK 15, I used to compile with arguments --enable-preview --release 15 passed to javac on my Ant build. Everything compiled and run fine.

When using JDK 16, if I compile with the same arguments, I get

error: invalid source release 15 with --enable-preview (preview language features are only supported for release 16)

Records are a standard feature of JDK 16, so I expected that I should compile without those arguments. However, If I remove them, I get

Foo.class uses preview features of Java SE 15. (use --enable-preview to allow loading of classfiles which contain preview features)

And Ant reports a compilation failure:

Compile failed; see the compiler error output for details. at org.apache.tools.ant.taskdefs.Javac.compile(Javac.java:1425)

So, its a compilation failure with the flags and without them. What's wrong?

1

There are 1 answers

3
Arvind Kumar Avinash On

error: invalid source release 15 with --enable-preview (preview language features are only supported for release 16)

Since you are using JDK-16, you have to use 16 as the value of --release (usually for any feature which is available in JDK-16 as a preview feature). Thus, the following will work for you:

javac --enable-preview --release 16 MyClass.java

However, record is a standard feature in Java-16 and therefore you do not need to compile your code with --enable-preview parameter. You can compile your code without using this parameter i.e.

javac MyClass.java

Foo.class uses preview features of Java SE 15. (use --enable-preview to allow loading of classfiles which contain preview features)

This is not a compile-time error. You get it when trying to run a .java class compiled with --enable-preview parameter, directly. You can run it as

java --enable-preview MyClass

Compile failed; see the compiler error output for details. at org.apache.tools.ant.taskdefs.Javac.compile(Javac.java:1425)

You need to update your JAVA_HOME setting to point to JDK-16 in order for ant to use JDK-16.