1. groovyc, the Groovy compiler
groovyc is the Groovy compiler command line tool. It allows you to compile Groovy sources into bytecode. It plays
the same role as javac in the Java world. The easiest way to compile a Groovy script or class is to run the following command:
groovyc MyClass.groovy
This will produce a MyClass.class file (as well as other .class files depending on the contents of the source). groovyc supports
a number of command line switches:
| Short version | Long version | Description | Example |
|---|---|---|---|
-cp |
-classpath, --classpath |
Specify the compilation classpath. Must be the first argument. |
groovyc -cp lib/dep.jar MyClass.groovy |
-sourcepath |
--sourcepath |
Accepted, and ignored. The compiler does not search this path. |
|
--temp |
Temporary directory for the compiler |
||
--encoding |
Encoding of the source files |
groovyc --encoding utf-8 script.groovy |
|
--help |
Displays help for the command line groovyc tool |
groovyc --help |
|
-d |
Specify where to place generated class files. |
groovyc -d target Person.groovy |
|
--check |
Check sources for errors without writing class files. Every check runs, including class verification and bytecode generation. |
groovyc --check Person.groovy |
|
-v |
--version |
Displays the compiler version |
groovyc -v |
-e |
--exception |
Displays the stack trace in case of compilation error |
groovyc -e script.groovy |
-w |
--warningLevel |
Sets how many warnings are reported after a successful compile: |
groovyc -w 2 MyClass.groovy |
-j |
--jointCompilation* |
Enables joint compilation |
groovyc -j A.groovy B.java |
-b |
--basescript |
Base class name for scripts (must derive from Script) |
|
-cf |
--configscript |
Advanced compiler configuration script |
groovyc --configscript config/config.groovy src/Person.groovy |
--error-format |
How errors and warnings are rendered: |
groovyc --error-format=short Person.groovy |
|
-t |
--tolerance |
The number of non-fatal errors to collect before compilation is abandoned. Defaults to |
groovyc -t 0 Person.groovy |
-Jname=value |
Passes |
groovyc -j -Jrelease=17 A.groovy B.java |
|
-Fflag |
Flag passed to |
groovyc -j -Fnowarn A.groovy B.java |
|
-pa |
--parameters |
Generates metadata for reflection on method parameter names. Defaults to false. |
groovyc --parameters Person.groovy |
-pr |
--enable-preview |
Enables preview features of the JDK running the compiler. Must follow |
groovyc --enable-preview Person.groovy |
-de |
--debug |
Prints extra information when compilation fails. |
groovyc --debug Person.groovy |
-s |
--stubDirectory |
Directory for the Java stubs written during joint compilation. |
groovyc -j -s stubs A.groovy B.java |
-ks |
--keepStubs |
Keeps the joint-compilation stubs instead of deleting them. |
groovyc -j --keepStubs A.groovy B.java |
--compile-static |
Compiles with |
groovyc --compile-static Person.groovy |
|
--type-checked |
Compiles with |
groovyc --type-checked Person.groovy |
|
@argfile |
Read options and source files from specified file. |
groovyc @conf/args |
Notes: * for a full description of joint compilation, see the joint compilation section.
2. Compiler warnings
While compiling, Groovy may report warnings: diagnostics that don’t stop compilation
but flag code that is suspicious or unlikely to behave as intended — for example, an
unreachable main method or a property that can’t override a final accessor. On a
successful compile, groovyc prints any collected warnings to stderr, using the same
format (message, source line and caret) as compilation errors, followed by a summary count.
Every warning carries an importance, and the -w (--warningLevel) option controls how
many are reported. Only warnings whose importance is at or below the configured level are
kept, so a lower level is quieter:
| Level | Name | Reports |
|---|---|---|
|
none |
No warnings at all. |
|
likely errors |
(default) Diagnostics that very probably indicate a mistake — for example an unreachable |
|
possible errors |
The above, plus diagnostics that often have benign causes — for example a field hidden by a dynamic property under |
|
paranoia |
The above, plus any remaining lower-priority warnings. |
For example, to also see the level 2 warnings:
groovyc -w 2 MyClass.groovy
The warning level can also be set programmatically via
CompilerConfiguration#setWarningLevel, or for the groovy command through the
groovy.warnings system property. Displaying the collected warnings on a successful
compile is done by the groovyc command line; other embeddings (for instance, code
driving a CompilationUnit directly) can instead read them from the unit’s ErrorCollector.
|
3. Ant task
See the groovyc Ant task documentation. It allows the Groovy compiler to be invoked from Apache Ant.
4. Gant
Gant is a tool for scripting Ant tasks using Groovy instead of XML to specify the logic. As such, it has exactly the same features as the Groovyc Ant task.
6. Maven integration
There are several approaches to compiling Groovy code in your Maven projects. GMavenPlus is the most flexible and feature rich, but like most Groovy compiler tools, it can have difficulties with joint Java-Groovy projects (for the same reason GMaven and Gradle can have issues). The Groovy-Eclipse compiler plugin for Maven sidesteps the joint compilation issues. Read this for a deeper discussion of the benefits and disadvantages of the two approaches.
A third approach is to use Maven’s Ant plugin to compile a groovy project. Note that the Ant plugin is bound to the compile and test-compile phases of the build in the example below. It will be invoked during these phases and the contained tasks will be carried out which runs the Groovy compiler over the source and test directories. The resulting Java classes will coexist with and be treated like any standard Java classes compiled from Java source and will appear no different to the JRE, or the JUnit runtime.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycomp.MyGroovy</groupId>
<artifactId>MyGroovy</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Maven Example building a Groovy project</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
<type>pom</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<configuration>
<target>
<mkdir dir="${basedir}/src/main/groovy"/>
<taskdef name="groovyc"
classname="org.codehaus.groovy.ant.Groovyc">
<classpath refid="maven.compile.classpath"/>
</taskdef>
<mkdir dir="${project.build.outputDirectory}"/>
<groovyc destdir="${project.build.outputDirectory}"
srcdir="${basedir}/src/main/groovy/" listfiles="true">
<classpath refid="maven.compile.classpath"/>
</groovyc>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<configuration>
<target>
<mkdir dir="${basedir}/src/test/groovy"/>
<taskdef name="groovyc"
classname="org.codehaus.groovy.ant.Groovyc">
<classpath refid="maven.test.classpath"/>
</taskdef>
<mkdir dir="${project.build.testOutputDirectory}"/>
<groovyc destdir="${project.build.testOutputDirectory}"
srcdir="${basedir}/src/test/groovy/" listfiles="true">
<classpath refid="maven.test.classpath"/>
</groovyc>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
This assumes you have a Maven project setup with groovy subfolders
as peers to the java src and test subfolders. You can use the java/jar
archetype to set this up then rename the java folders to groovy or keep
the java folders and just create groovy peer folders. There exists, also
a groovy plugin which has not been tested or used in production. After
defining the build section as in the above example, you can invoke the
typical Maven build phases normally. For example, mvn test will
execute the test phase, compiling Groovy source and Groovy test source
and finally executing the unit tests. If you run mvn jar it will
execute the jar phase bundling up all of your compiled production
classes into a jar after all the unit tests pass. For more detail on
Maven build phases consult the Maven documentation. Groovy 4 and later
are published under the groupId org.apache.groovy. The <target> element
is the configuration used by Maven AntRun Plugin 3; AntRun 1 used <tasks>.
6.1. GMaven and GMavenPlus
6.1.1. GMaven
GMaven is the original Maven plugin for Groovy, supporting both compiling and scripting Groovy.
Important:
You should be aware that GMaven is not supported anymore and can have difficulties with joint compilation. GMavenPlus can be a good replacement, but if you are having problems with joint compilation, you might consider the Groovy Eclipse maven plugin.
6.1.2. GMavenPlus
GMavenPlus is a rewrite of GMaven and is in active development. It supports most of the features of GMaven (a couple notable exceptions being mojo Javadoc tags and support for older Groovy versions). Its joint compilation uses stubs (which means it has the same potential issues as GMaven and Gradle). The main advantages over its predecessor are that it supports recent Groovy versions, InvokeDynamic, Groovy on Android, GroovyDoc, and configuration scripts.
6.2. The Groovy Eclipse Maven plugin
Groovy-Eclipse provides a compiler plugin for Maven. Using the compiler plugin, it is possible to compile your maven projects using the Groovy-Eclipse compiler. One feature unavailable elsewhere is stubless joint compilation.
7. Joint compilation
Joint compilation means that the Groovy compiler will parse the Groovy source files, create stubs for all of them, invoke the Java compiler to compile the stubs along with Java sources, and then continue compilation in the normal Groovy compiler way. This allows mixing of Java and Groovy files without constraint.
Joint compilation can be enabled using the -j flag with the command-line compiler,
or using a nested tag and all the attributes and further nested tags as required
for the Ant task.
It is important to know that if you don’t enable joint compilation and try to compile Java source files with the Groovy compiler, the Java source files will be compiled as if they were Groovy sources. In some situations, this might work since most of the Java syntax is compatible with Groovy, but there are a number of places where semantics could be different.
8. Android support
Groovy code can run on Android 8.0 (API level 26) and later. Groovy compiles
dynamic calls to invokedynamic, which the Android toolchain only accepts from
API level 26, so an application using Groovy must set minSdk to 26 or higher.
Earlier Android versions are not supported.
Android support is experimental. The Android runtime (ART) does not provide
java.lang.invoke.SwitchPoint, which the Groovy runtime uses to invalidate call
sites, so an application currently has to supply its own implementation of that class.
|
No Groovy-specific Android Gradle plugin is needed. The groovy-android-gradle-plugin referenced by earlier versions of this guide targets old releases of the Android Gradle Plugin, and older Groovy versions, and is not required with current tooling. Instead:
-
Put the Groovy code in a plain Groovy library module. The groovy compiler compiles it on the JVM against the
android.jarstubs of the Android SDK, using the regular Groovy jar. -
Make the Android application module depend on that library like any other jar. D8 converts the Groovy class files to DEX.
-
At run time, use the Android flavour of the Groovy runtime, which has a classifier of
grooid. It is the regular jar with thejava.beansclasses, which Android lacks, replaced by a repackaged copy of OpenBeans. Gradle can also select it through theorg.apache.groovy:groovy-grooidcapability.
The library module compiles against the regular jar:
plugins {
id 'groovy'
}
dependencies {
compileOnly 'org.apache.groovy:groovy:6.0.1'
compileOnly files("$sdkDir/platforms/android-36/android.jar")
}
The application module supplies the grooid jar at run time:
android {
defaultConfig {
minSdk 26
}
}
dependencies {
implementation project(':mylibrary')
runtimeOnly 'org.apache.groovy:groovy:6.0.1:grooid'
}
Only the groovy and groovy-test modules have a grooid variant. Other modules,
such as groovy-json, are used as they are. Exclude their transitive dependency on
the regular groovy jar, because the grooid jar takes its place:
dependencies {
implementation('org.apache.groovy:groovy-json:6.0.1') {
exclude group: 'org.apache.groovy', module: 'groovy'
}
}
When a release build shrinks the application with R8, the classes and members that
Groovy looks up reflectively must be kept, including any type the application calls
dynamically. The reachability metadata that the Groovy jars ship under
META-INF/native-image is a good starting point for the keep rules. Statically
compiled code (@CompileStatic) relies less on reflection and is easier to shrink.