Apache Groovy is a powerful multi-faceted programming language for the JVM platform
npx @tessl/cli install tessl/maven-org-codehaus-groovy--groovy@3.0.0Apache Groovy is a powerful multi-faceted programming language for the JVM platform that supports a spectrum of programming styles incorporating features from dynamic languages such as optional and duck typing, but also static compilation and static type checking at levels similar to or greater than Java. It aims to greatly increase developer productivity with many powerful features but also a concise, familiar and easy to learn syntax.
pom.xml:
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>3.0.25</version>
</dependency>build.gradle:
implementation 'org.codehaus.groovy:groovy:3.0.25'Common Java imports for using Groovy:
import groovy.lang.*;
import groovy.util.*;For Groovy scripts:
import groovy.transform.*
import groovy.util.*import groovy.lang.GroovyShell;
import groovy.lang.Script;
import groovy.lang.Binding;
// Execute Groovy code dynamically
GroovyShell shell = new GroovyShell();
Script script = shell.parse("println 'Hello from Groovy!'");
script.run();
// Execute with variable bindings
Binding binding = new Binding();
binding.setVariable("name", "World");
shell.setProperty("binding", binding);
Object result = shell.evaluate("return \"Hello ${name}!\"");
System.out.println(result); // Prints: Hello World!Groovy's architecture consists of several key components:
groovy.lang): Fundamental language constructs (GroovyObject, Closure, Script, MetaClass)org.codehaus.groovy.runtime): Method dispatch, type coercion, and runtime supportorg.codehaus.groovy.ast): Abstract syntax tree for compilation and meta-programminggroovy.transform): Compile-time code generation and AST transformationsgroovy.util): Configuration, XML processing, CLI tools, and data structuresEssential runtime classes and interfaces that enable Groovy's dynamic behavior, meta-programming capabilities, and integration with the JVM. Includes the fundamental GroovyObject interface, closures, scripts, and meta-class system.
interface GroovyObject {
Object invokeMethod(String name, Object args);
Object getProperty(String propertyName);
void setProperty(String propertyName, Object newValue);
MetaClass getMetaClass();
void setMetaClass(MetaClass metaClass);
}
class GroovyShell {
Script parse(String scriptText);
Object evaluate(String scriptText);
Object run(String scriptText, String[] args);
}
class Closure<V> {
V call();
V call(Object... args);
Closure<V> curry(Object... args);
Closure<V> memoize();
}Abstract Syntax Tree classes and compilation support for programmatic code generation, AST transformations, and compile-time meta-programming. Essential for building Groovy-based tools and IDEs.
class ASTNode {
int getLineNumber();
int getColumnNumber();
String getText();
}
class ClassNode extends ASTNode {
String getName();
List<MethodNode> getMethods();
List<FieldNode> getFields();
List<PropertyNode> getProperties();
}
class AstBuilder {
List<ASTNode> buildFromString(String source);
List<ASTNode> buildFromCode(Closure closure);
}Configuration file parsing, XML processing, command-line interface building, and data structure utilities. Includes ConfigSlurper for application configuration and XML processing tools.
class ConfigSlurper {
ConfigObject parse(String text);
ConfigObject parse(URL location);
void setEnvironment(String environment);
}
class XmlSlurper {
GPathResult parse(String xml);
GPathResult parse(File file);
GPathResult parseText(String xml);
}
class CliBuilder {
OptionAccessor parse(String[] args);
void usage();
}Configuration and Data Processing
Enhanced collection classes, observable data structures, and utility functions that extend Java's collection framework with Groovy-specific features and dynamic behavior.
class ObservableList<E> extends ArrayList<E> {
void addPropertyChangeListener(PropertyChangeListener listener);
void removePropertyChangeListener(PropertyChangeListener listener);
}
class Node {
String name();
Object value();
Map<String, String> attributes();
List<Node> children();
Node parent();
}
class ListWithDefault<T> {
static <T> ListWithDefault<T> withDefault(List<T> list, Closure defaultValue);
T getDefaultValue(int index);
}Compile-time code generation annotations that automatically add common functionality like toString(), equals(), builders, immutability, and static compilation support.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
@interface CompileStatic { }
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
@interface Immutable {
String[] excludes() default {};
boolean copyWith() default false;
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
@interface ToString {
String[] excludes() default {};
boolean includeNames() default false;
boolean includeFields() default false;
}Comprehensive XML parsing, navigation, and generation capabilities including both tree-based (XmlParser) and streaming (XmlSlurper) approaches with GPath expression support.
class XmlParser {
Node parse(String xml);
Node parse(File file);
Node parseText(String xml);
}
class MarkupBuilder {
MarkupBuilder(Writer writer);
Object invokeMethod(String name, Object args);
}
abstract class GPathResult {
String text();
int size();
GPathResult children();
GPathResult parent();
GPathResult find(Closure closure);
GPathResult findAll(Closure closure);
}Time arithmetic, date manipulation, and duration calculations through category-based extensions to Java's Date and temporal classes.
class TimeCategory {
static Date plus(Date date, BaseDuration duration);
static Date minus(Date date, BaseDuration duration);
static BaseDuration minus(Date lhs, Date rhs);
}
class TimeDuration extends BaseDuration {
int getDays();
int getHours();
int getMinutes();
int getSeconds();
}Comprehensive JSON parsing, generation, and manipulation capabilities through JsonSlurper for parsing JSON data and JsonBuilder for creating JSON output with full type safety and streaming support.
class JsonSlurper {
Object parseText(String text);
Object parse(Reader reader);
Object parse(File file);
void setType(JsonParserType type);
}
class JsonBuilder {
JsonBuilder();
JsonBuilder(Object content);
void call(Closure closure);
String toString();
}
enum JsonParserType {
CHARACTER_SOURCE, LAX, INDEX_OVERLAY
}Comprehensive database connectivity, query execution, and data manipulation through the Groovy SQL API. Provides simplified database access with automatic resource management, transaction support, and result set navigation.
class Sql {
static Sql newInstance(String url, String user, String password, String driver);
List<GroovyRowResult> rows(String sql);
void eachRow(String sql, Closure closure);
int executeUpdate(String sql);
void withTransaction(Closure closure);
}
interface GroovyRowResult extends Map<String, Object> {
Object getProperty(String columnName);
Object getAt(int columnIndex);
}Comprehensive testing framework with enhanced JUnit integration, mocking capabilities, and Groovy-specific assertion utilities. Provides GroovyTestCase for improved test organization and mock objects for isolation testing.
abstract class GroovyTestCase extends TestCase {
void shouldFail(Closure code);
void shouldFail(Class<? extends Throwable> expectedType, Closure code);
void assertScript(String script);
Object evaluate(String script);
}
class MockFor {
MockFor(Class clazz);
void demand(String methodName);
Object use(Closure closure);
}Comprehensive templating system with multiple engines for generating dynamic text output. Includes SimpleTemplateEngine for basic templating, GStringTemplateEngine for GString-based templates, and specialized engines for XML/HTML generation with streaming support.
class SimpleTemplateEngine extends TemplateEngine {
Template createTemplate(String templateText);
Template createTemplate(Reader reader);
}
interface Template {
Writable make(Map binding);
Writable make();
}
class MarkupTemplateEngine extends TemplateEngine {
MarkupTemplateEngine(TemplateConfiguration configuration);
Template createTypeCheckedTemplate(String templateText);
}Enhanced file system operations, stream processing, and I/O utilities through Groovy extensions to Java's I/O classes. Provides simplified file manipulation, automatic resource management, and powerful text processing capabilities.
class File {
String getText();
void setText(String text);
File eachLine(Closure closure);
Object withReader(Closure closure);
Object withWriter(Closure closure);
void eachFileRecurse(Closure closure);
}
class InputStream {
String getText();
byte[] getBytes();
void copyTo(OutputStream target);
}Grape dependency management system for dynamic dependency resolution and loading, including @Grab annotation support for declaring dependencies in scripts.
class Grape {
static void grab(String endorsedModule);
static void grab(Map<String, Object> dependency);
static void addResolver(Map<String, Object> args);
static URI[] resolve(Map<String, Object> args);
}
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
@interface Grab {
String group() default "";
String module();
String version();
String classifier() default "";
}interface MetaClass {
Object invokeMethod(Object object, String methodName, Object[] arguments);
Object getProperty(Object object, String propertyName);
void setProperty(Object object, String propertyName, Object newValue);
boolean respondsTo(Object obj, String name);
MetaProperty hasProperty(Object obj, String name);
}
class Binding {
Object getVariable(String name);
void setVariable(String name, Object value);
Map<String, Object> getVariables();
boolean hasVariable(String name);
}
class GString implements CharSequence {
String toString();
Object[] getValues();
String[] getStrings();
}
interface Range<T> extends List<T> {
T getFrom();
T getTo();
boolean contains(Object obj);
int size();
}
class Tuple implements List<Object> {
Object get(int index);
int size();
Tuple subTuple(int startIndex, int endIndex);
}class ConfigObject extends LinkedHashMap<String, Object> {
ConfigObject flatten();
ConfigObject merge(ConfigObject other);
void writeTo(Writer writer);
}
interface OptionAccessor {
boolean hasOption(String opt);
String getOptionValue(String opt);
String[] getOptionValues(String opt);
List<?> getArgList();
}class MethodNode extends ASTNode {
String getName();
Parameter[] getParameters();
ClassNode getReturnType();
Statement getCode();
int getModifiers();
}
class FieldNode extends ASTNode {
String getName();
ClassNode getType();
Expression getInitialExpression();
int getModifiers();
}
class PropertyNode extends ASTNode {
String getName();
ClassNode getType();
Statement getGetterBlock();
Statement getSetterBlock();
FieldNode getField();
}