繁体   English   中英

什么是Groovy相当于Python的dir()?

[英]What's the Groovy equivalent to Python's dir()?

在Python中,我可以看到对象有哪些方法和字段:

print dir(my_object)

什么是Groovy中的相同(假设它有一个)?

在Groovy看起来特别好看(未经测试, 取自此链接,因此代码信用应该去那里):

// Introspection, know all the details about classes :
// List all constructors of a class
String.constructors.each{println it}

// List all interfaces implemented by a class
String.interfaces.each{println it}

// List all methods offered by a class
String.methods.each{println it}

// Just list the methods names
String.methods.name

// Get the fields of an object (with their values)
d = new Date()
d.properties.each{println it}

你正在寻找的一般术语是内省

如上所述这里 ,找到字符串对象定义的所有方法:

 "foo".metaClass.methods*.name.sort().unique()

它不像Python版本那么简单,也许其他人可以展示出更好的方式。

除了使用普通的Java反射API之外,还有:

http://docs.codehaus.org/display/GROOVY/JN3535-Reflection

您还可以使用元类玩游戏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM