code
docs
tests
Groovy Scripting Library
The Groovy Scripting Library is a Generic mixin that implements interfaces by delegating to Groovy code from classpath resources.
But before looking at how to use the Scripting library we’ll see that you don’t need this library at all if you simply need to use Groovy classes as Fragments. Then we’ll see how to use Groovy class scripts and method scripts.
All examples below are based on this type:
public interface HelloSpeaker { String sayHello( String name ); }
To directly use compiled Groovy classes as Fragments you don’t need this library at all.
Having this Groovy class compiled ;
HelloSpeakerMixin.groovy.
public class HelloSpeakerMixin implements HelloSpeaker { public String sayHello( String name ) { "Hello $name!" } }
assemble it directly:
SingletonAssembler assembler = new SingletonAssembler() { @Override public void assemble( ModuleAssembly module ) throws AssemblyException { module.transients( HelloSpeaker.class ).withMixins( HelloSpeakerMixin.class ); } }; HelloSpeaker speaker = assembler.module().newTransient( HelloSpeaker.class ); Assert.assertEquals( "Hello World!", speaker.sayHello( "World" ) );
Declare a Groovy class in a classpath resource file located in the same package as the implemented type with the name <type>.groovy
:
HelloSpeaker.groovy.
class HelloSpeaker { def This def sayHello( name ) { "Hello $name!".toString() } }
Then assemble it with the GroovyMixin
:
SingletonAssembler assembler = new SingletonAssembler() { @Override public void assemble( ModuleAssembly assembly ) throws AssemblyException { assembly.transients( HelloSpeaker.class ).withMixins( GroovyMixin.class ); } }; HelloSpeaker speaker = assembler.module().newTransient( HelloSpeaker.class ); Assert.assertEquals( "Hello World!", speaker.sayHello( "World" ) );
Groovy class scripts get @This
injection in a This
property if present.
Implement single composites methods, each in a classpath resource file located in the same package as the implemented type with the name <type>.<method>.groovy
:
HelloSpeaker.sayHello.groovy.
"Hello ${args[0]}!".toString()
Then assemble it with the GroovyMixin
:
SingletonAssembler assembler = new SingletonAssembler() { @Override public void assemble( ModuleAssembly assembly ) throws AssemblyException { assembly.transients( HelloSpeaker.class ).withMixins( GroovyMixin.class ); } }; HelloSpeaker speaker = assembler.module().newTransient( HelloSpeaker.class ); Assert.assertEquals( "Hello World!", speaker.sayHello( "World" ) );
Groovy method scripts get @This
injection as This
property and the methods arguments array as args
.