7

I have a custom Maven plugin which makes use of JDK 12 preview features. I compile the plugin setting --enable-preview as compiler arg, i.e.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArgs>
            <compilerArg>--enable-preview</compilerArg>
        </compilerArgs>
    </configuration>
</plugin>

When I want to execute the plugin, I add the plugin like this in the POM:

<plugin>
    <groupId>my.group</groupId>
    <artifactId>my-plugin</artifactId>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>my-goal</goal>
            </goals>
        </execution>
    </executions>
</plugin>

But this fails with:

Preview features are not enabled for MyPluginMojo. Try running with '--enable-preview'

How can I enable preview features in a plugin execution?

Giovanni Lovato
  • 2,183
  • 2
  • 29
  • 53
  • Simple answer you can not...cause a plugin is executed within the context of a given build which uses a given JDK ...I don't know why you are using preview features of a JDK within a plugin ? Does not make sense from my point of view...Apart from that this means you can not run your build with earlier JDK version by using the implemented plugin ...? – khmarbaise Sep 20 '19 at 07:14
  • 1
    Just wanted to start using the new switch statement; if it's not possible to enable preview features on a plugin execution, I'll just don't use them! Thanks! – Giovanni Lovato Sep 20 '19 at 07:18
  • See also [Compile a JDK12 preview feature with Maven](https://stackoverflow.com/q/52232681/1744774). – Gerold Broser Sep 22 '19 at 10:00

3 Answers3

5

For me, I had to add a config file to my build directory at:

.mvn/jvm.config

containing:

--enable-preview

This will make sure that Maven passes the correct parameters to JVM

Randgalt
  • 2,907
  • 1
  • 17
  • 31
  • I've added this file but still getting errors. Any help? "error: records are a preview feature and are disabled by default." – renanleandrof Jun 18 '21 at 16:43
2

You made a mistake in your pom. <compilerArgs> takes nested <arg>, like so:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>17</source>
                <target>17</target>
                <compilerArgs>
                    <arg>--enable-preview</arg>
                 </compilerArgs>
            </configuration>
        </plugin>
Aleksandr Dubinsky
  • 22,436
  • 15
  • 82
  • 99
0

For JDK 17, this works for me:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <source>17</source>
    <target>17</target>
    <compilerArgs>--enable-preview</compilerArgs>
  </configuration>
</plugin>