Opal
Opal

Reputation: 84844

Groovy - extensions structure

I'd like to extend String's asType method to handle LocalDateTime. I know how to override this method, however I've no idea where should I put it in project structure to work globally - for all strings in my project. Is it enough to put such extension wherever in the classpath? I know that there's a special convention for extensions (META-INF/services), how does it work for method overriding?

Upvotes: 4

Views: 1012

Answers (1)

Opal
Opal

Reputation: 84844

All documentation regarding this topic can be found here. And here exactly the relevant part can be found.

Module extension and module descriptor

For Groovy to be able to load your extension methods, you must declare your extension helper classes. You must create a file named org.codehaus.groovy.runtime.ExtensionModule into the META-INF/services directory:

org.codehaus.groovy.runtime.ExtensionModule moduleName=Test module for specifications moduleVersion=1.0-test extensionClasses=support.MaxRetriesExtension staticExtensionClasses=support.StaticStringExtension The module descriptor requires 4 keys:

moduleName : the name of your module

moduleVersion: the version of your module. Note that version number is only used to check that you don’t load the same module in two different versions.

extensionClasses: the list of extension helper classes for instance methods. You can provide several classes, given that they are comma separated.

staticExtensionClasses: the list of extension helper classes for static methods. You can provide several classes, given that they are comma separated.

Note that it is not required for a module to define both static helpers and instance helpers, and that you may add several classes to a single module. You can also extend different classes in a single module without problem. It is even possible to use different classes in a single extension class, but it is recommended to group extension methods into classes by feature set.

Module extension and classpath

It’s worth noting that you can’t use an extension which is compiled at the same time as code using it. That means that to use an extension, it has to be available on classpath, as compiled classes, before the code using it gets compiled. Usually, this means that you can’t have the test classes in the same source unit as the extension class itself. Since in general, test sources are separated from normal sources and executed in another step of the build, this is not an issue.

Upvotes: 2

Related Questions