有人知道如何在 Groovy 中打印闭包的源代码吗?
例如,我有这个闭包(绑定(bind)到 a
)
def a = { it.twice() }
我想要String
“it.twice()”或“{ it.twice() }”
仅仅一个简单的 toString
当然是行不通的:
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() }
但是
您将需要运行时类路径中可用的脚本的源代码,如
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"
并且
text 技巧并不真正返回相同的代码,只是返回类似于 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, 2, 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.
行号至少应该接近原始代码
关于groovy - 在 Groovy 中打印闭包定义/源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263008/