views:

46

answers:

2

How can I print out the (public and internal) variables and their values of a Groovy object?

I.e

class X
{
  def X = 10
  def Y = 5

  private void doPrivate()
  {
      def Z = 3
  }
}

Should give

X, 10
Y, 5
Z, 3

This has to be a dynamic solution, i.e at runtime.

A: 

You mean like this?

def a = "Hi"

a.properties.each { println "$it.key -> $it.value" }

Gives:

class -> class java.lang.String
bytes -> [72, 105]
empty -> false

[edit]

With your edited question, this would give you:

class -> class X
y -> 5
metaClass -> org.codehaus.groovy.runtime.HandleMetaClass@16de4e1[groovy.lang.MetaClassImpl@16de4e1[class X]]
x -> 10

I don't think it's possible to get the Z value at runtime... The only way I can think of to do it is via the AST...

tim_yates
+1  A: 

dump()

For example

"ddd".dump()

Prints:

java.lang.String@2ef900 value=dddd offset=0 count=4 hash=3078400

Don
Be sure to light a match when you're finished
Don