Gradle extensions and enum types

I am creating a gradle plugin with a custom extension:

project.extensions.create("myExtension", MyExtension.class)

      

Where MyExtension looks like this:

class MyExtension {
  Set<MyEnum> mySet;
  MyEnum myEnum;
}

      

The problem is I cannot install mySet

inside my build.gradle (with standard DSL):

myExtension {
    myEnum = 'enumField1'
    mySet = ['enumField1']
}

      

I java.lang.String cannot be cast to MyEnum

only get for mySet, String to enum conversion works well for myEnum ... So I'm gessing if it's possible for a collection of type enum? Is there a solution?

+3


source to share


2 answers


I get it to work using a simple java array instead of a generic one Collection<T>

:

class MyExtension {
  // string convertion doesn't work
  Set<MyEnum> mySet;
  // string convertion works fine
  MyEnum[] myArray;
  MyEnum myEnum;
}

      

The extension can then be used as expected:



myExtension {
    myEnum = 'enumField1'
    mySet = ['enumField1']
}

      

hope this helps ...

+2


source


It works for myEnum

because Groovy automatically converts strings assigned to enum properties. To do the same job for mySet

, you'll need to add a method to the extension that takes the string, converts it to the appropriate enumeration value (a simple cast would be done in Groovy), and adds the latter to the set. You will also have to initialize the set.



+3


source







All Articles