As an example of overriding invokeMethod for static methods, take this simple example:
- class Stuff {
- static InvokeMe() {
- "foo"
- }
- def invokeMe()
- {
- "stuff"
- }
- def methodMissing(String name, args)
- {
- printf("Missing Method Name='%s' with input Argument(s):\n", name, args.getClass().getName())
- for(def arg:args) printf("\t%s (%s)\n", arg, arg.class.name)
- "miss"
- }
- }
- Stuff.metaClass.'static'.invokeMethod = { String name, args ->
- def metaMethod = Stuff.metaClass.getStaticMetaMethod(name, args)
- printf("%sMethod Name='%s' with input Argument(s):\n", metaMethod==null?"Missing ":"", name, args.getClass().getName())
- for(def arg:args) printf("\t%s (%s)\n", arg, arg.class.name)
- def result
- if(metaMethod) result = metaMethod.invoke(delegate,args)
- else {
- result = "static miss"
- }
- result
- }
- assert "foo" == Stuff.InvokeMe()
- assert "static miss" == Stuff.doStuff("Test", 123)
- Stuff s = new Stuff()
- assert "stuff" == s.invokeMe()
- assert "miss" == s.invokeAny(123, "test")
So what is happening here? Well firstly we've overridden invokeMethod using the 'static' qualifier and by assigning it an appropriate closure, but in addition we first look-up a MetaMethod with the line:
- def metaMethod = delegate.class.metaClass.getStaticMetaMethod(name)
Adding properties
Properties can be added in a couple of ways. Firstly you can use the instance method syntax seen previously:
- class Book {
- String title
- }
- Book.metaClass.getAuthor << {-> "Stephen King" }
- def b = new Book(title:"The Stand")
- assert "Stephen King" == b.author
- def properties = Collections.synchronizedMap([:])
- Book.metaClass.setAuthor = { String value ->
- properties[System.identityHashCode(delegate) + "author"] = value
- }
- Book.metaClass.getAuthor = {->
- properties[System.identityHashCode(delegate) + "author"]
- }
Alternatively you can simply assign a value as follows:
- Book.metaClass.author = "Stephen King"
- def b = new Book("The Stand")
- assert "Stephen King" == b.author
Supplement
* Using metMissing & propertyMissinhodg
沒有留言:
張貼留言