今天写了个读取类的函数的签名的脚本,供学习之用,其实最主要是想看看Groovy都给类添加了些什么函数。
代码就二十多行,从中又可以体现出Groovy代码之精炼
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(显示所有字段)