Skip to content
Skip to breadcrumbs
Skip to header menu
Skip to action menu
Skip to quick search
Quick Search
Browse
Pages
Blog
Labels
Attachments
Mail
Advanced
What’s New
Space Directory
Feed Builder
Keyboard Shortcuts
Confluence Gadgets
Log In
Sign Up
Dashboard
Groovy
Copy Page
You are not logged in. Any changes you make will be marked as
anonymous
. You may want to
Log In
if you already have an account. You can also
Sign Up
for a new account.
This page is being edited by
.
Paragraph
Paragraph
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Preformatted
Quote
Bold
Italic
Underline
More colours
Strikethrough
Subscript
Superscript
Monospace
Clear Formatting
Bullet list
Numbered list
Outdent
Indent
Align left
Align center
Align right
Link
Table
Insert
Insert Content
Image
Link
Attachment
Symbol
Emoticon
Wiki Markup
Horizontal rule
tinymce.confluence.insert_menu.macro_desc
Info
JIRA Issue
Status
Gallery
Tasklist
Table of Contents
Other Macros
Page Layout
No Layout
Two column (simple)
Two column (simple, left sidebar)
Two column (simple, right sidebar)
Three column (simple)
Two column
Two column (left sidebar)
Two column (right sidebar)
Three column
Three column (left and right sidebars)
Undo
Redo
Find/Replace
Keyboard Shortcuts Help
<p>Groovy is a great language just on its own in various scenarios. It is also extremely useful in mixed Groovy/Java environments. With this in mind, Groovy has been designed to be very lightweight and easy to embed into any Java application system.</p> <p>There are three main approaches for natively integrating Groovy with Java. Each of these is discussed in more detail below.</p> <p>Alternatively, you can use the <a class="confluence-link" href="/display/GROOVY/Bean+Scripting+Framework" data-linked-resource-id="2725" data-linked-resource-type="page" data-linked-resource-default-alias="Bean Scripting Framework" data-base-url="http://docs.codehaus.org">Bean Scripting Framework</a> to embed any scripting language into your Java code, giving you other language options if you needed them (though we can't imagine why <img class="emoticon emoticon-smile" data-emoticon-name="smile" border="0" src="/s/en_GB/3278/15/_/images/icons/emoticons/smile.png" alt="(smile)" title="(smile)" /> ). Using BSF allows you to be more loosely coupled to your scripting language; however, native integration is more light weight and offers closer integration.</p> <h2>Evaluate scripts or expressions using the shell</h2> <p>You can evaluate any expression or script in Groovy using the <a href="http://groovy.codehaus.org/api/groovy/lang/GroovyShell.html">GroovyShell</a>.<br /> The GroovyShell allows you to pass in and out variables via the <a href="http://groovy.codehaus.org/api/groovy/lang/Binding.html">Binding</a> object. <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> // call groovy expressions from Java code Binding binding = new Binding(); binding.setVariable("foo", new Integer(2)); GroovyShell shell = new GroovyShell(binding); Object value = shell.evaluate("println 'Hello World!'; x = 123; return foo * 10"); assert value.equals(new Integer(20)); assert binding.getVariable("x").equals(new Integer(123)); </pre></td></tr></table> <h2>Evaluate Scripts with a Common Base Class</h2> <p>It is often useful to make your groovy scripts extend a base class of your choosing so that the script can access common methods. This can be achieved by setting the script base class property on the compile configuration and passing this new compiler configuration to the shell.</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> class ScriptBaseTest { @Test void extend_groovy_script() { def compiler = new CompilerConfiguration() compiler.setScriptBaseClass("ScriptBaseTestScript") def shell = new GroovyShell(this.class.classLoader, new Binding(), compiler) assertEquals shell.evaluate("foo()"), "this is foo" } } abstract class ScriptBaseTestScript extends Script { def foo() { "this is foo" } } </pre></td></tr></table> <h2>Dynamically loading and running Groovy code inside Java</h2> <p>You can use the <a href="http://groovy.codehaus.org/api/groovy/lang/GroovyClassLoader.html">GroovyClassLoader</a> to load classes dynamically into a Java program and execute them (or use them) directly. The following Java code shows an example: <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class groovyClass = loader.parseClass(new File("src/test/groovy/script/HelloWorld.groovy")); // let's call some method on an instance GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); Object[] args = {}; groovyObject.invokeMethod("run", args); </pre></td></tr></table> <p>If you have an interface you wish to use which you implement in the Groovy script you can use it as follows:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> GroovyClassLoader gcl = new GroovyClassLoader(); Class clazz = gcl.parseClass(myStringwithGroovyClassSource, "SomeName.groovy"); Object aScript = clazz.newInstance(); MyInterface myObject = (MyInterface) aScript; myObject.interfaceMethod(); ... </pre></td></tr></table> <p>This works fine if the Groovy class implements the inferface MyInterface. myObject can from then on be used as every other Java object implementing MyInterface.</p> <p>One thing to remember is that the parseClass will try to create an object from your String fileName. Another way to do the gcl.parseClass is:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> Class clazz = gcl.parseClass(new File("SomeName.groovy"); </pre></td></tr></table> <p>Full Example:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> TestInterface.java public interface TestInterface { public void printIt(); } Tester.groovy public class Tester implements TestInterface { public void printIt() { println "this is in the test class"; } } TestClass.java -- inside of a method String fileName = "Tester.groovy"; GroovyClassLoader gcl = new GroovyClassLoader(); Class clazz = gcl.parseClass(new File(fileName)); Object aScript = clazz.newInstance(); TestInterface ifc = (TestInterface) aScript; ifc.printIt(); </pre></td></tr></table> <p>Note that all of the error handling has been removed -- you won't be able to do this in a java class. I actually use the Interface invocation for Groovy inside of a Utility Class.</p> <h2>The GroovyScriptEngine</h2> <p>The most complete solution for people who want to embed groovy scripts into their servers and have them reloaded on modification is the GroovyScriptEngine. You initialize the GroovyScriptEngine with a set of CLASSPATH like roots that can be URLs or directory names. You can then execute any Groovy script within those roots. The GSE will also track dependencies between scripts so that if any dependent script is modified the whole tree will be recompiled and reloaded.</p> <p>Additionally, each time you run a script you can pass in a Binding that contains properties that the script can access. Any properties set in the script will also be available in that binding after the script has run. Here is a simple example:</p> <p>/my/groovy/script/path/hello.groovy:</p> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> output = "Hello, ${input}!" </pre></td></tr></table> <table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; String[] roots = new String[] { "/my/groovy/script/path" }; GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding = new Binding(); binding.setVariable("input", "world"); gse.run("hello.groovy", binding); System.out.println(binding.getVariable("output")); </pre></td></tr></table> <p>This will print "Hello, world!".</p> <h2>Embedding a Groovy Console in a Java Application</h2> <p>An interactive Groovy interpreter can be embedded in a running application for experimentation and testing. For a tutorial on how to do, including example code, see the cookbook example <a href="http://groovy.codehaus.org/Embedding+a+Groovy+Console+in+a+Java+Server+Application">Embedding a Groovy Console in a Java Server Application</a>.</p> <p>An example for the integration of Groovy as scripting language into an application can be found at <a class="confluence-link" href="/display/GROOVY/Integrating+Groovy+in+an+application+-+a+success+story" data-linked-resource-id="73650" data-linked-resource-type="page" data-linked-resource-default-alias="Integrating Groovy in an application - a success story" data-base-url="http://docs.codehaus.org">Integrating Groovy in an application - a success story</a></p> <h2>Runtime dependencies</h2> <p>As well as Java 1.4 and the Groovy jar we also depend at runtime on the ASM library constituted of five jars (asm-2.2.jar, asm-attrs-2.2.jar, asm-analysis-2.2, asm-tree-2.2.jar, and asm-util-2.2.jar) plus the ANTLR library (antlr-2.7.5.jar). That's it. So just add these 7 jars to your classpath and away you go, you can happily embed Groovy into your application.</p> <p>Alternatively, instead of several jars, you can use groovy-all-1.0-beta-x.jar included in the GROOVY_HOME/embeddable directory of your distribution: this jar contains both Groovy and ASM combined in a single and convenient archive, with the ASM classes in a different namespace, so conflicts with other libraries also using ASM will be avoided <img class="emoticon emoticon-smile" data-emoticon-name="smile" border="0" src="/s/en_GB/3278/15/_/images/icons/emoticons/smile.png" alt="(smile)" title="(smile)" /></p>
Please type the word appearing in the picture.
Attachments
Labels
Location
Watch this page
< Edit
Preview >
Loading…
Save
Cancel
Next hint
search
attachments
weblink
advanced