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>This is an example of how to replace a MetaClass to adjust the default behavior. Each groovy object has a metaClass that is used to manage the dynamic nature of the language. This class intercepts calls to groovy objects to ensure that the appropriate grooviness can be added. For example, when an object is constructed, the MetaClass's invokeConstructor()is called. One feature of the invokeConstructor allows us to create groovy objects using a map argument to set the properties of the object (new X([prop1: value1, prop2: value2])).</p><p>These solutions perform complete replacements, where as a more scoped solution can be found at <a class="confluence-link" href="/display/GROOVY/Using+the+Proxy+Meta+Class" data-linked-resource-id="71589" data-linked-resource-type="page" data-linked-resource-default-alias="Using the Proxy Meta Class" data-base-url="http://docs.codehaus.org">Using the Proxy Meta Class</a>.</p><p><strong>InvokeHelper Solution</strong> </p><p>This technique installs the meta class at runtime using the InvokerHelper to gain access to the registry which allows us to change the meta class instance that is in use. The behaviour for objects created before the change depends on whether they are Java or Groovy objects. Groovy objects "cache" their metaclass, so once they're created, changing the registry has no effect. However, Java objects don't have a cache, so accesses to them always start with a trip to the registry, meaning any registry changes affect existing and new instances alike.</p><p>This sample code overrides the invokeMethod method to augment the behavior but there are other options that you can choose from like set and getAttribute, invokeStaticMethod and invokeConstructor. The complete list can be found in the Groovy's source release in "src/main/groovy/lang/DelegatingMetaClass.java".</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>import org.codehaus.groovy.runtime.InvokerHelper class DelegatingMetaClassInvokeHelperTest extends GroovyTestCase { void testReplaceMetaClass() { /* * Constructing first instance before meta class replacment * is made. */ def firstInstance = "first" assertEquals "first", firstInstance.toString() def myMetaClass = new MyDelegatingMetaClass(String.class) InvokerHelper.metaRegistry.setMetaClass(String.class, myMetaClass) /* * Constructing second instance after meta class replacment * is made. */ def secondInstance = "second" /* * Since we are replacing a meta class at the class level * we are changing the behavior of the first and second * instance of the string. */ assertEquals "changed first", firstInstance.toString() assertEquals "changed second", secondInstance.toString() } } class MyDelegatingMetaClass extends groovy.lang.DelegatingMetaClass { MyDelegatingMetaClass(final Class aclass) { super(aclass); initialize() } public Object invokeMethod(Object a_object, String a_methodName, Object[] a_arguments) { return "changed ${super.invokeMethod(a_object, a_methodName, a_arguments)}" } } </pre></td></tr></table><p><strong>Package Name Convention Solution</strong><br /> This second solution offers a more consistent augmentation of existing classes. There are no risks of unpredictable results from methods. The idea is that any package.class can have a custom meta class loaded at startup time by placing it into a well known package with a well known name. <br class="atl-forced-newline" /> <br class="atl-forced-newline" /> </p><p> groovy.runtime.metaclass.[YOURPACKAGE].[YOURCLASS]MetaClass</p><p>So your class Foo in package "bar" could have a custom meta class FooMetaClass in package "groovy.runtime.metaclass.bar".</p><p>The following example shows how we can change the behavior of the String class. Firstly the custom meta class, similar to the implementation above except that it needs a MetaClassRegistry argument in its constructor.</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>package groovy.runtime.metaclass.java.lang class StringMetaClass extends groovy.lang.DelegatingMetaClass { StringMetaClass(MetaClass delegate) { super(delegate); } public Object invokeMethod(Object a_object, String a_methodName, Object[] a_arguments) { return "changed ${super.invokeMethod(a_object, a_methodName, a_arguments)}" } } </pre></td></tr></table><p>The actual class that uses the enhanced features is now very simple. Notice that there are no extra imports or any work with the meta class. The mere package and name of the class tells the groovy runtime to use the custom meta class.</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 DelegatingMetaClassPackageImpliedTest extends GroovyTestCase { void testReplaceMetaClass() { assertEquals "changed hello world", "hello world".toString() } } </pre></td></tr></table><p><strong>Precedence</strong></p><p>So what would happen if you used both techniques. Assume that the package convention class exists in your class path and you create and set another meta class. The answer is that the last setMetaClass that you did applies to the usages of all instance of the effected type. <br class="atl-forced-newline" /> </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