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 d
Having a function you can call on an object itself is convenient but doesn't exist out of the box. If you don't mind polluting the namespace on Object
's metaClass, you can monkey patch it with something like this:
Object.metaClass.printit { -> println org.codehaus.groovy.runtime.InvokerHelper.toString(delegate) }
'asdf'.printit() // prints 'asdf'
printit
isn't the greatest name, but print
, println
and dump
are all taken.
dump()
For example
println "ffffd".dump()
Prints:
java.lang.String@2ef900 value=ffffdd offset=0 count=4 hash=3078400
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...