Last active
December 19, 2015 10:09
-
-
Save alanland/5938529 to your computer and use it in GitHub Desktop.
Groovy MOP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mop | |
class RowSet { | |
Map map = [:] | |
void update(key,value){ | |
map.put(key,value) | |
} | |
def get(key){ | |
map.get(key) | |
} | |
} | |
// Using methodMissing with dynamic method registration | |
class GORM { | |
def dynamicMethods = [] // an array of dynamic methods that use regex | |
def methodMissing(String name, args) { | |
def method = dynamicMethods.find { it.match(name) } | |
if(method) { | |
GORM.metaClass."$name" = { Object[] varArgs -> | |
method.invoke(delegate, name, varArgs) | |
} | |
return method.invoke(delegate,name, args) | |
} | |
else throw new MissingMethodException(name, delegate, args) | |
} | |
} | |
// property getter | |
class Foo2 { | |
def propertyMissing(String name) { name } | |
} | |
// property getter and setter | |
class Foo1 { | |
def storage = [:] | |
def propertyMissing(String name, value) { storage[name] = value } | |
def propertyMissing(String name) { storage[name] } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mop | |
//http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing | |
//http://stackoverflow.com/questions/7078855/groovy-dynamically-add-properties-to-groovy-classes-from-inside-class-methods | |
class Run extends GroovyTestCase { | |
void test1() { | |
RowSet.metaClass.each = { Closure closure -> | |
Map map = delegate.map | |
if (map != null && map.size() > 0) { | |
map.each { k, v -> | |
closure.call(k, v) | |
} | |
} | |
// closure.call(delegate) | |
} | |
def rst = new RowSet(map: ['a': 1, 'b': 2, 'c': 'ccc']) | |
rst.each { k, v -> | |
println "$k,$v" | |
} | |
} | |
void test2() { | |
RowSet.metaClass.invokeMethod = { String name, args -> | |
def m = RowSet.metaClass.getMetaMethod(name, args) | |
if (m!=null) | |
return m.invoke(delegate, args) | |
return delegate.get(name) | |
} | |
RowSet.metaClass.propertyMissing={String name-> | |
return Math.random() | |
} | |
def rst = new RowSet(map: ['-1':'abc','a': 1, 'b': 2, 'c': 'ccc']) | |
// method | |
println rst.'-1'() | |
println rst.'a'() | |
println rst.a() | |
// property | |
println rst.a | |
println(rst.bcde) | |
println rst.a | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment