`
JohnnyJian
  • 浏览: 104324 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Groovy学习笔记——读取类的函数签名的脚本

阅读更多

今天写了个读取类的函数的签名的脚本,供学习之用,其实最主要是想看看Groovy都给类添加了些什么函数。

代码就二十多行,从中又可以体现出Groovy代码之精炼smile

 

PrintClass.groovy:

if (args) {
    def className = args[0]
    def theClass = Class.forName(className)
    def theMetaClass = theClass.metaClass
    def printClass = { property ->
        println "The $property of $className:"
        if (theClass.class.metaClass.hasProperty(theClass, property))
            theClass."$property".each { println it }
        else if (theMetaClass.metaClass.hasProperty(theMetaClass, property))
            theMetaClass."$property".each { println it }
    }
    if (args.size() == 1)
        args = ['methods', 'metaMethods', 'constructors']
    else
        args = args[1..-1]
    args.eachWithIndex { arg, index ->
        if (index > 0)
            println()
        printClass(arg)
    }
} else {
    println 'Print out the informations of the specified class.'
    println 'Usage: PrintClass class-full-name [methods] [metaMethods] [constructors]'
}

 

用法:

PrintClass java.lang.Integer 或者 PrintClass java.lang.Integer metaMethods 等等

其实除了函数签名,还可以显示其他东西,譬如:PrintClass java.lang.Integer declaredFields(显示所有字段)

分享到:
评论
1 楼 agile_boy 2008-02-05  
嗯,Groovy的动态特性用起来还是很舒服的。

相关推荐

Global site tag (gtag.js) - Google Analytics