基于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(){"{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.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可以很大的简化开发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南