简体   繁体   中英

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

In Python I can see what methods and fields an object has with:

print dir(my_object)

What's the equivalent of that in Groovy (assuming it has one)?

Looks particulary nice in Groovy (untested, taken from this link so code credit should go there):

// 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.

Besides just using the normal Java reflection API, there's:

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

You can also play games with the metaclasses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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