Groovy Power Print

前端 未结 2 1864
情书的邮戳
情书的邮戳 2021-01-24 11:37

Groovy has a power assert, but I\'d like a power print. For example,

def foo = \'banna5\', monkey=7, x=70
println \"foo=$foo, monkey=$monkey, x/2=${x/2}\"
         


        
2条回答
  •  天命终不由人
    2021-01-24 12:23

    This may or may not work for you. it's Very Possible that it only works in scripts.

    def pprint(def varClosure) {
        s=varClosure()
        print("\"$s\" = " + binding.variables[s])
    }
    
    test = 15
    
    pprint{"test"}
    

    I used a closure so it would pass the current context in (to get bindings). You can iterate over the closure in various ways--for instance if you pass pprint{["test","anotherVar"]} you could use this in stead of the println:

    s.each() { print("\"$it\" = ${binding.variables[s]},\t") }
    println ""
    

    That would give pretty close to the results you wanted.

    If you want to do it with a groovy class the bindings hash doesn't exist. There is a properties hash, but it only accesses object properties (not all variables available to the closure--in other words it would miss variables defined in the method and parameters).

    Perhaps the closure has a hash of all properties available to it--that would be perfect. I'll look more later.

    Also there is a dump() method on object that you might enjoy.

提交回复
热议问题