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:
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:
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:
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:
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:
- class Stuff {
- def invokeMe() { "foo" }
- }
- Stuff.metaClass.invokeMethod = { String name, args ->
- def metaMethod = Stuff.metaClass.getMetaMethod(name,args)
- def result
- if(metaMethod) result = metaMethod.invoke(delegate,args)
- else {
- result = "bar"
- }
- result
- }
- def stf = new Stuff()
- assert "foo" == stf.invokeMe()
- assert "bar" == stf.doStuff()
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:
- class Book {
- String title
- @Override
- public String toString(){return "Book:'${title}'"}
- }
- Book.metaClass.static.Create << { String title -> new Book(title:title) }
- def b = Book.Create("The Stand")
- printf("${b}")
沒有留言:
張貼留言