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>Initially developed under the Grailsumbrella and integrated back into Groovy 1.5, ExpandoMetaClass is a very handy way for changing the runtime behavior of your objects and classes, instead of writing full-blow MetaClass classes. Each time, we want to add / change several properties or methods of an existing type, there is too much of a repetition of Type.metaClass.xxx. Take for example this extract of a Unit manipulation DSL dealing with operator overloading:</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> Number.metaClass.multiply = { Amount amount -> amount.times(delegate) } Number.metaClass.div = { Amount amount -> amount.inverse().times(delegate) } Amount.metaClass.div = { Number factor -> delegate.divide(factor) } Amount.metaClass.div = { Amount factor -> delegate.divide(factor) } Amount.metaClass.multiply = { Number factor -> delegate.times(factor) } Amount.metaClass.power = { Number factor -> delegate.pow(factor) } Amount.metaClass.negative = { -> delegate.opposite() } </pre></td></tr></table> <p>The repetition, here, looks obvious. But with the ExpandoMetaClass DSL, we can streamline the code by regrouping the operators per type:</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> Number.metaClass { multiply { Amount amount -> amount.times(delegate) } div { Amount amount -> amount.inverse().times(delegate) } } Amount.metaClass { div << { Number factor -> delegate.divide(factor) } div << { Amount factor -> delegate.divide(factor) } multiply { Number factor -> delegate.times(factor) } power { Number factor -> delegate.pow(factor) } negative { -> delegate.opposite() } } </pre></td></tr></table> <p>A metaClass() method takes a closure as single argument, containing the various definitions of the methods and properties, instead of repeating the Type.metaClass on each line. When there is just one method of a given name, use the pattern methodName<br /> { /* closure */ }, but when there are several, you should use the append operator and follow the patten methodName <<<br /> { /* closure */ }. Static methods can also be added through this mechanism, so instead of the classical approach:</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> // add a fqn() method to Class to get the fully // qualified name of the class (ie. simply Class#getName) Class.metaClass.static.fqn = { delegate.name } assert String.fqn() == "java.lang.String" </pre></td></tr></table> <p>You can now do:</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.metaClass { 'static' { fqn { delegate.name } } } </pre></td></tr></table> <p>Note here that you have to quote the statickeyword, to avoid this construct to look like a static initializer. For one off method addition, the classical approach is obviously more concise, but when you have several methods to add, the EMC DSL makes sense.</p> <p>The usual approach for adding properties to existing classes through ExpandoMetaClass is to add a getter and a setter as methods. For instance, say you want to add a method that counts the number of words in a text file, you could try this:</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> File.metaClass.getWordCount = { delegate.text.split(/\w/).size() } new File('myFile.txt').wordCount </pre></td></tr></table> <p>When there is some logic inside the getter, this is certainly the best approach, but when you just want to have new properties holding simple values, through the ExpandoMetaClass DSL, it is possible to define them. In the following example, a lastAccessed property is added to a Car class — each instance will have its property. Whenever a method is called on that car, this property is updated with a newer timestamp.</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 Car { void turnOn() {} void drive() {} void turnOff() {} } Car.metaClass { lastAccessed = null invokeMethod = { String name, args -> def metaMethod = delegate.metaClass.getMetaMethod(name, args) if (metaMethod) { delegate.lastAccessed = new Date() metaMethod.doMethodInvoke(delegate, args) } else { throw new MissingMethodException(name, delegate.class, args) } } } def car = new Car() println "Last accessed: ${car.lastAccessed ?: 'Never'}" car.turnOn() println "Last accessed: ${car.lastAccessed ?: 'Never'}" car.drive() sleep 1000 println "Last accessed: ${car.lastAccessed ?: 'Never'}" sleep 1000 car.turnOff() println "Last accessed: ${car.lastAccessed ?: 'Never'}" </pre></td></tr></table> <p>In our example, in the DSL, we access that property through the delegate of the closure, with delegate.lastAccessed = new Date(). And we intercept any method call thanks to invokeMethod(), delegating to the original method for the call, and throwing an exception in case the method doesn't exist. Later on, you can see by executing this script that lastAccessed is updated as soon as we call a method on our instance. </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