简体   繁体   English

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

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

In Python I can see what methods and fields an object has with: 在Python中,我可以看到对象有哪些方法和字段:

print dir(my_object)

What's the equivalent of that in Groovy (assuming it has one)? 什么是Groovy中的相同(假设它有一个)?

Looks particulary nice in Groovy (untested, taken from this link so code credit should go there): 在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}

The general term you are looking for is introspection . 你正在寻找的一般术语是内省

As described here , to find all methods defined for String object: 如上所述这里 ,找到字符串对象定义的所有方法:

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

It's not as simple as Python version, perhaps somebody else can show better way. 它不像Python版本那么简单,也许其他人可以展示出更好的方式。

Besides just using the normal Java reflection API, there's: 除了使用普通的Java反射API之外,还有:

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

You can also play games with the metaclasses. 您还可以使用元类玩游戏。

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

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