Java Integration and Embedding Groovy
39.1 Mixed Java/Groovy Projects
Joint compilation: groovyc -j (or Gradle's groovy plugin) compiles Java and Groovy sources that reference each other.
Groovy classes are ordinary JVM classes: Java can instantiate them and call their methods and properties (getX()/setX()).
Calling dynamic Groovy features from Java: GroovyObject.invokeMethod, or InvokerHelper.
39.2 Embedding Groovy in Java Applications
Use cases: rule engines, configuration-as-code, user scripting, plugin systems, test fixtures.
Sandbox untrusted scripts with SecureASTCustomizer, @TimedInterrupt, a restricted classloader, and ideally process isolation (Module 46).
// GroovyShell: evaluate expressions and scripts
Binding binding = new Binding();
binding.setVariable("x", 10);
GroovyShell shell = new GroovyShell(binding);
Object result = shell.evaluate("x * 2 + 1"); // 21
// GroovyClassLoader: load classes from source at runtime (plugins)
GroovyClassLoader gcl = new GroovyClassLoader();
Class<?> clazz = gcl.parseClass(new File("Plugin.groovy"));
Object plugin = clazz.getDeclaredConstructor().newInstance();
// GroovyScriptEngine: script folders with dependency tracking and auto-reload
GroovyScriptEngine gse = new GroovyScriptEngine(new String[]{"scripts/"});
gse.run("hello.groovy", binding);
// JSR-223 (javax.script)
ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
engine.put("name", "Ana");
engine.eval("println \"Hello, $name\"");39.3 Groovy and Modern Java Features
Lambdas and method references (Groovy 3+), records and sealed types (Groovy 4), switch expressions, text blocks (Groovy's triple quotes), var, virtual threads (any JDK 21 API works), JPMS modules (Groovy 4 fixed split packages).