Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Code Block
titleStringStaticExtension.java
languagejava
import java.util.UUID;


/**
 * Static extension methods for the String class
 */
public class StringStaticExtension {
    public static String randomUUID(String selfType) {
        return UUID.randomUUID().toString();
    }
}

...

Technically, the previous description about how to add extension methods to an existing class is a user-friendly way of doing it, but Groovy doesn't force you to use this standard mechanism. If you want to, you can write your own extension module implementation class, given that a module returns a list of MetaMethods to be added to a class. However, implementing such a module is not easy, and won't be covered by this tutorial. If you need to do that, please refer to the org.codehaus.groovy.runtime.m12n.ExtensionModule and org.codehaus.groovy.runtime.m12n.ExtensionModuleRegistry classes.

 

FAQ

Are extension modules compatible with type checking?

Yes, if the extension descriptor and the extension class is found on compilation classpath.

Are extension modules compatible with static compilation ?

Yes, if the extension descriptor and the extension class is found on compilation classpath.

When I compile my project using Gradle and @CompileStatic, my code using an extension module fails compilation.

As of Gradle 1.4, Gradle's native Groovy compiler integration doesn't seem to be compatible with extension modules. A fix is available in Groovy 2.1.2. As a workaround, you can use the Ant compiler integration:

Code Block
compileGroovy.groovyOptions.useAnt = true
compileTestGroovy.groovyOptions.useAnt = true

See https://jira.codehaus.org/browse/GROOVY-6008