Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out variables and values in a Groovy object

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.

like image 816
geejay Avatar asked Jun 18 '10 12:06

geejay


People also ask

How do I print values in a Groovy script?

You can print the current value of a variable with the println function.

How do I return a value in Groovy?

The last line of a method in Groovy is automatically considered as the return statement. For this reason, an explicit return statement can be left out. To return a value that is not on the last line, the return statement has to be declared explicitly.

Can we use echo in Groovy?

Note that echo does not work in Groovy itself - only in Jenkins. println works in both.

Which method is used to print the value of a variable?

print() method is used. The System. out. println() method, in Java, prints the value passed as the parameter to it, on the console screen and the changes the cursor to the next line on the console.


2 Answers

dump()

For example

println "ddd".dump() 

Prints:

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

like image 179
Dónal Avatar answered Sep 16 '22 23:09

Dónal


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

like image 40
tim_yates Avatar answered Sep 19 '22 23:09

tim_yates