2

我是 Groovy 的新手。我想实现这一点:

def a = { assert 1 == 1 }

def method(def a)
{
    println a
}
method(a)

现在println打印ConsoleScript1$_run_closure1@72e9108f。但我希望它会打印assert 1 == 1。那可能吗?

4

3 回答 3

6

使用我链接到的答案作为 this 的副本,如果您保存:

import groovy.inspect.swingui.AstNodeToScriptVisitor

def a = { assert 1 == 1 }

def method( def a ) {
  new StringWriter().with { writer ->
    a.metaClass.classNode.getDeclaredMethods("doCall")[0].code.visit new AstNodeToScriptVisitor( writer )
    println "{\n$writer}"
  }
}

method( a )

到一个文件test.groovy然后做:

groovy test.groovy

你得到输出:

{
assert 1 == 1 : null
return null
}

我认为这与您将要获得的一样接近...不使用 code变量中的位置数据(这是一个Groovy 语句类)来获取行/列号并将文件解析为文本以提取它.. .

于 2012-10-01T11:20:48.017 回答
1

您正在寻找类似 Javascript 的功能,其中在函数上调用 toString() 将打印其源代码。

Groovy 被编译为 JVM 字节码。groovy 编译器不会将源代码保留在已编译的 JVM 类文件中。

于 2012-10-01T11:01:03.533 回答
0

在 Odersky & Co. 的《Programming in Scala》一书中有一个用 Scala 编写的著名示例。

基本上,您必须:

  • 列出文件
  • 对于每个匹配 *.groovy 的文件
  • 修剪/grep 想要的行

Groovy SDK中,有一个 Groovy 方法directory.eachFileMatch可以让您找到正确的文件,还有一个File.filterLine()方法可以让您抓取正确的行。

于 2012-10-01T11:22:25.690 回答