Search code examples
javaenumsmaven-plugin

Using a Java enum as a Maven mojo property


I'm building a custom Maven plugin and would like one of the configuration parameters of the mojo to be driven by a Java enum. I've searched all over the web and cannot seem to find any indication of how/whether this is possible, short of references to an "MNG-4292" ticket (ref) which seem to imply it is possible but the links are dead.

I tried creating an enum

public enum MyEnum {
    NONE,
    DIRECT,
    INCREMENT
}

and then using it on a @Parameter annotation

import org.apache.maven.plugin.AbstractMojo;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.util.Enumeration;
import java.util.Properties;

/**
 * My Mojo.
 */
@Mojo(name = "sync", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true)
public class MyMojo extends AbstractMojo {

  @Parameter(defaultValue = MyEnum.DIRECT)
  private MyEnum pickOne;

  ...
}

However, I get IDE errors like:

Type mismatch: cannot convert from MyEnum to String

Can anyone explain how/if you can use a Java enum on a Maven mojo parameter?


Solution

  • Attribute defaultValue of @Parameter annotation is a String type.

    All plugins parameter in pom.xml and/or in command line are provided as String, so defaultValue is also a String type.
    Maven convert parameters from String to destination type in runtime. Here is list of common converters: https://maven.apache.org/guides/mini/guide-configuring-plugins.html#Configuring_Parameters

    For annotation attribute you must provide a constant value, so in your case it must be:

    @Parameter(defaultValue = "DIRECT")
    

    For Enums Maven will use Enum.valueOf(String) for convert this value in runtime.


    ASF project JIRA has address: https://issues.apache.org/
    Correct address for mentioned issues is: https://issues.apache.org/jira/browse/MNG-4292