Dark theme | Light theme

December 16, 2009

Groovy Goodness: Getting Information About Objects

To get some information about an object we often use the toString() method in Java. In Groovy we can use the same toString() method, but we have two more alternatives. We can use the dump() method on an object and we get information about the name of the object, the hashcode and the values of the fields. And we can use the inspect() method, which will try to return a String which matches closest what we would type in Groovy code to create the object.

def map = [username: 'mrhaki']
assert '["username":"mrhaki"]' == map.inspect()

def list = [1, 2, 3, 'Groovy']
assert '[1, 2, 3, "Groovy"]' == list.inspect()

def range = 0..10
assert '0..10' == range.inspect()

def str = 'Inspecting object with Groovy'
assert '"Inspecting object with Groovy"' == str.inspect()

def dom = groovy.xml.DOMBuilder.newInstance().parseText('<root><language>Groovy</language></root>')
println dom.documentElement.inspect()
// Output:
// <?xml version="1.0" encoding="UTF-8"?>
// <root>
//   <language>Groovy</language>
// </root>