基于JVM的动态语言Groovy MetaProgramming 知识集

Metaprogramming 使groovy动态语言的特性发挥的淋漓尽致(Metaprogramming is writing code that has the ability to dynamicallychange its behavior at runtime.)

如下是这方面的知识一个汇总

1. 类Discovering the Class

def s = "Hello"

printlns.class

printlns.getClass()

String.constructors.each{println it}

println ""

String.interfaces.each{println it}

println ""

2. 域Discovering the Fields of a Class

def d = new Date()

printlnd.properties

println ""

d.properties.each{println it}

println ""

d.class.declaredFields.each{println it}

println ""

//重要的对象metaClass

printlnDate.metaClass

3. 域存在性检查Checking for the Existence of a Field

class Person{

String firstname

String lastname

String toString(){"${firstname} ${lastname}"}

MetaPropertyhasProperty(String property){

return this.metaClass.hasProperty(this, property)

}

}

def person = new Person()

def request = [firstname: "bill", lastname: "gates"]

request.each{name, value->

if(person.metaClass.hasProperty(person, name)){

//if(person.hasProperty(name)){

person.setProperty(name, value)

}

}

println person

4. 方法Discovering the Methods of a Class

def d = new Date()

d.class.methods.each{println it}

d.class.methods.name

println ""

//evaluate run in a new shell

d.class.methods.each{method ->

if(method.name.startsWith("get")){

print "${method.name}: "

evaluate("dd = new Date(); println dd.${method.name}()")

}

}

println ""

//

def binding = new Binding()

binding.setVariable("d", d)

defgs = new GroovyShell(binding)

d.class.methods.each{method ->

if(method.name.startsWith("get")){

print "${method.name}: "

gs.evaluate("println d.${method.name}()")

}

}

println ""

//GString (most concise way to dynamically call a method on a class)

d.class.methods.each{method ->

if(method.name.startsWith("get")){

print "${method.name}: "

println d."${method.name}"()

}

}

println ""

5. 方法存在性检查Checking for the Existence of a Method

class Greeting{

defsayHello(){

println "Hello, Stranger"

}

defsayHello(String name){

println "Hello, ${name}"

}

}

def g = new Greeting()

if(g.metaClass.respondsTo(g, "sayHello", null)){

g.sayHello()

}

if(g.metaClass.respondsTo(g, "sayHello", String)){

g.sayHello("Jane")

}

println "Number of sayHello() methods: " + g.metaClass.respondsTo(g, "sayHello").size()

g.metaClass.respondsTo(g, "sayHello").each{m ->

println "${m.name} ${m.nativeParameterTypes}"

}

6. 域指针Creating a Field Pointer

def p = new Person()

p.name = "Jane"

println p.name

//Field Pointer, 可以操作privtate

printlnp.@name

7. 方法指针Creating a Method Pointer

def list = []

def insert = list.&add

insert "Java"

insert "Groovy"

println list

8. Calling Methods That Don’t Exist (invokeMethod)

class Person{

String name

Map relationships = [:]

Object invokeMethod(String what, Object who){

if(relationships.containsKey(what)){

who.each{thisPerson ->

relationships.get(what).add(thisPerson)

}

}

else{

relationships.put(what,who as List)

}

}

}

defscott = new Person(name:"Scott")

scott.married "Kim"

scott.knows "Neal"

scott.workedWith "Brian"

scott.knows "Venkat"

scott.workedWith "Jared"

scott.knows "Ted", "Ben", "David"

printlnscott.relationships

9. Creating an Expando

def e = new Expando()

e.latitude = 70

e.longitude = 30

println e

e.areWeLost = {->

return (e.longitude != 30) || (e.latitude != 70)

}

printlne.areWeLost()

10. Adding Methods to a Class Dynamically (Categories)

Categories allow you to add new functionality to any class at runtime.

use(RandomHelper){

10.times{ println 10.rand() }

}

class RandomHelper{

static int rand(Integer self){

def r = new Random()

return r.nextInt(self.intValue())

}

}

use(InternetUtils){

println "http://localhost/".get()

println "http://search.yahoo.com/search".get("p=groovy")

defparams = [:]

params.n = "10"

params.vl = "lang_eng"

params.p = "groovy"

println "http://search.yahoo.com/search".get(params)

}

class InternetUtils{

static String get(String self){

return self.toURL().text

}

static String get(String self, String queryString){

defurl = self + "?" + queryString

return url.get()

}

static String get(String self, Map params){

def list = []

params.each{k,v->

list << "$k=" + URLEncoder.encode(v)

}

defurl = self + "?" + list.join("&")

return url.get()

}

}

11. Adding Methods to a Class Dynamically(ExpandoMetaClass)

Integer.metaClass.rand = {->

def r = new Random()

return r.nextInt(delegate.intValue())

}

5.times{ println 10.rand() }

String.metaClass.get = {->

return delegate.toURL().text

}

println "http://localhost/".get()

 

A category is perfect ifyou want to limit the scope of your new methods to a well-defined blockof code. An ExpandoMetaClass is better if you want to have your newmethods applied to all instances across the entire running application.

If you want your new functionality to be easily shared by both Java andGroovy code, categories leave you with a plain old Java class with staticmethods. ExpandoMetaClasses are more closely tied to Groovy, but theyare significantly more performant as well.

以上可以作为使用的一个参考,在使用反射等这类应用时,使用groovy可以很大的简化开发

posted @ 2011-04-11 21:52  2012  阅读(737)  评论(0编辑  收藏  举报