Retrieving content closure in groovy

I am new to Groovy. I want to achieve this:

def a = { assert 1 == 1 } def method(def a) { println a } method(a) 

println now prints ConsoleScript1$_run_closure1@72e9108f . But I would like it to print assert 1 == 1 . Is it possible?

+1
source share
3 answers

Using the answer to which I am bound as a duplicate of this if you save:

 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 ) 

into the test.groovy file, then do:

 groovy test.groovy 

You get the conclusion:

 { assert 1 == 1 : null return null } 

Be that as it may, I think ... Without using positional data in the code variable (which is the Groovy Class Statement ) to get the row / column numbers and parse the file as text to extract it ...

+5
source

You are looking for Javascript-like functionality in which calling the toString () function for a function will print the source code.

Groovy compiled into JVM bytecode. The groovy compiler does not save the source code in a compiled JVM class file.

+1
source

A well-known example is written in Scala in Odersky and Co.'s book "Scala Programming"

Basically, you need:

  • specify files
  • for each file matching * .groovy
  • trim / grep required lines

in the Groovy SDK there is the Groovy directory.eachFileMatch method, which allows you to find the correct file, and File.filterLine() , which allows you to capture the correct lines.

0
source

Source: https://habr.com/ru/post/969418/


All Articles