加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Groovy中打印关闭定义/源

发布时间:2020-12-14 16:35:04 所属栏目:大数据 来源:网络整理
导读:谁知道如何打印Groovy的关闭源? 例如,我有这个关闭(绑定到一个) def a = { it.twice() } 我想有字符串“it.twice()”或“{it.twice()}” 只是一个简单的toString ofcourse不行: a.toString(); //results in: Script1$_run_closure1_closure4_closure6@12f1
谁知道如何打印Groovy的关闭源?

例如,我有这个关闭(绑定到一个)

def a = { it.twice() }

我想有字符串“it.twice()”或“{it.twice()}”

只是一个简单的toString ofcourse不行:

a.toString(); //results in: Script1$_run_closure1_closure4_closure6@12f1bf0

解决方法

简短的答案是你不能.长的答案是:
取决于你需要的代码,你可能会逃避

// file: example1.groovy
def a = { it.twice() }
println a.metaClass.classNode.getDeclaredMethods("doCall")[0].code.text
// prints: { return it.twice() }


您将需要类路径AT RUNTIME中可用脚本的源代码,如下所述

groovy.lang.MetaClass#getClassNode()
“Obtains a reference to the original
AST for the MetaClass if it is
available at runtime
@return The
original AST or null if it cannot be
returned”


文本技巧并不真正返回相同的代码,只是一个代码,如AST的表示,可以在这个脚本中看到

// file: example2.groovy
def b = {p-> p.twice() * "p"}
println b.metaClass.classNode.getDeclaredMethods("doCall")[0].code.text
// prints: { return (p.twice() * p) }

仍然,它可能是有用的,因为它是如果你只是想快速看看

而且,如果你手上有太多时间,不知道该怎么办,可以编写自己的org.codehaus.groovy.ast.GroovyCodeVisitor来打印它

或者,只是窃取一个现有的,像groovy.inspect.swingui.AstNodeToScriptVisitor

// file: example3.groovy
def c = {w->
  [1,2,3].each {
    println "$it"
    (1..it).each {x->
      println 'this seems' << ' somewhat closer' << ''' to the 
      original''' << " $x"
    }
  }
}
def node = c.metaClass.classNode.getDeclaredMethods("doCall")[0].code
def writer = new StringWriter()
node.visit new groovy.inspect.swingui.AstNodeToScriptVisitor(writer)
println writer
// prints: return [1,3].each({
//     this.println("$it")
//     return (1.. it ).each({ java.lang.Object x ->
//         return this.println('this seems' << ' somewhat closer' << ' to the n      original' << " $x")
//     })
// })

现在.
如果你想要原始的,准确的,可运行的代码…你没有运气
我的意思是,你可以使用源代码行信息,但是上一次我检查,并不是真的让他们正确

// file: example1.groovy
....
def code = a.metaClass.classNode.getDeclaredMethods("doCall")[0].code
println "$code.lineNumber $code.columnNumber $code.lastLineNumber $code.lastColumnNumber"
new File('example1.groovy').readLines()
... etc etc you get the idea.

行号应该至少在原始代码附近

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读