Groovy Power Print

前端 未结 2 1840
情书的邮戳
情书的邮戳 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:18

    There is nothing that does what you want currently in Groovy...

    The problem would be getting the names of the variables when you print out the values.

    The way that powerrassert seems to do it, is via AST manipulation of the bytecode (see line 947 of the class org.codehaus.groovy.classgen.AsmClassGenerator) to decorate the assert method with several classes inside the org.codehaus.groovy.runtime.powerassert package.

    So to get the results you require, something similar would have to be added to manipulate the AST in a similar way.

    You could add a new feature issue to the project's JIRA, and you never know...it might make it into future versions of Groovy

    But for now, I think you're stuck with your println as you have it above

    0 讨论(0)
  • 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.

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