Printing out variables and values in a Groovy object

前端 未结 3 1064
逝去的感伤
逝去的感伤 2020-12-14 14:35

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         


        
相关标签:
3条回答
  • 2020-12-14 15:17

    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.

    0 讨论(0)
  • 2020-12-14 15:20

    dump()

    For example

    println "ffffd".dump()
    

    Prints:

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

    0 讨论(0)
  • 2020-12-14 15:21

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

    0 讨论(0)
提交回复
热议问题