程式扎記: [ Groovy Doc ] ExpandoMetaClass - Runtime Discovery & Add static method (6)

標籤

2015年2月4日 星期三

[ Groovy Doc ] ExpandoMetaClass - Runtime Discovery & Add static method (6)

Runtime MetaClass Analysis
At runtime it is often useful to know what other methods or properties exist at the time the method is executed. To this end ExpandoMetaClass provides the following methods as of this writing:
getMetaMethod: Retrieves an instance MetaMethod for the given name and argument values, using the types of the argument values to establish the chosen MetaMethod
hasMetaMethod: Checks whether a MetaMethod for the given name and arguments exists
getMetaProperty: Looks up an existing MetaProperty by name
hasMetaProperty: Returns true if the MetaClass has the given property

Why can't you just use reflection? Well because Groovy is different, it has the methods that are "real" methods and methods that are available only at runtime. These are sometimes (but not always) represented as MetaMethods. The MetaMethods tell you what methods are available at runtime, thus your code can adapt. This is of particular use when overriding invokeMethod, getProperty and/or setProperty for example:
  1. class Stuff {  
  2.    def invokeMe() { "foo" }  
  3. }  
  4.   
  5. Stuff.metaClass.invokeMethod = { String name, args ->  
  6.    def metaMethod = Stuff.metaClass.getMetaMethod(name,args)  
  7.    def result  
  8.    if(metaMethod) result = metaMethod.invoke(delegate,args)  
  9.    else {  
  10.       result = "bar"  
  11.    }  
  12.    result  
  13. }  
  14.   
  15. def stf = new Stuff()  
  16.   
  17. assert "foo" == stf.invokeMe()  
  18. assert "bar" == stf.doStuff()  
Here we are using the getMetaMethod method to obtain a reference to a method that may or may not exist. If it doesn't exist the getMetaMethod method will return null and the code can adapt to this fact.

Adding static methods
Static methods can also be added using the same technique as instance methods with the addition of the "static" qualifier before the method name:
  1. class Book {  
  2.    String title  
  3.    @Override  
  4.    public String toString(){return "Book:'${title}'"}  
  5. }  
  6.   
  7. Book.metaClass.static.Create << { String title -> new Book(title:title) }  
  8.   
  9. def b = Book.Create("The Stand")  
  10. printf("${b}")  


沒有留言:

張貼留言

網誌存檔