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}")  


沒有留言:

張貼留言

[ Java 文章收集 ] 局部敏感哈希 (Locality-Sensitive Hashing, LSH) 方法介紹

Source From  Here   Preface   本文主要介紹一種用於海量高維數據的近似最近鄰快速查找技術—— 局部敏感哈希  ( Locality-Sensitive Hashing, LSH ),內容包括了 LSH 的原理、LSH 哈希函數集、以及 LSH 的一...