Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle plugin extension and enum types

I'm creating a gradle plugin with a custom extension :

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

Where MyExtension looks like :

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

The problem is that I'm not able to set mySet inside my build.gradle (with standard DSL) :

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

I get a java.lang.String cannot be cast to MyEnum only for mySet, the String to enum convertion works well for myEnum... So I'm gessing if it is possible for a Collection of enum type ? Is there a solution ?

like image 572
avianey Avatar asked Nov 11 '14 14:11

avianey


People also ask

What is EXT in build Gradle?

Extra properties extensions allow new properties to be added to existing domain objects. They act like maps, allowing the storage of arbitrary key/value pairs. All ExtensionAware Gradle domain objects intrinsically have an extension named “ ext ” of this type.

What is Gradle task type?

Gradle supports two types of task. One such type is the simple task, where you define the task with an action closure. We have seen these in Build Script Basics. For this type of task, the action closure determines the behaviour of the task. This type of task is good for implementing one-off tasks in your build script.

What is ProcessResources in Gradle?

Class ProcessResourcesCopies resources from their source to their target directory, potentially processing them. Makes sure no stale resources remain in the target directory.

What are Gradle plugins?

A plugin is simply any class that implements the Plugin interface. Gradle provides the core plugins (e.g. JavaPlugin ) as part of its distribution which means they are automatically resolved. However, non-core binary plugins need to be resolved before they can be applied.


2 Answers

It works for myEnum because Groovy automatically converts strings assigned to enum properties. To make the same work for mySet, you'll have to add a method to the extension that accepts a string, converts it to the corresponding enum value (a simple cast will do in Groovy), and adds the latter to the set. You'll also have to initialize the set.

like image 123
Peter Niederwieser Avatar answered Sep 28 '22 02:09

Peter Niederwieser


I get it to work by using a simple java array instead of generic 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 it helps...

like image 39
avianey Avatar answered Sep 28 '22 01:09

avianey