My linux world » Java – Groovy

Java - Groovy


Contents

Configuration

If you use maven, add this to your pom.xml:

<dependency>
  <groupId>org.codehaus.groovy</groupId>
  <artifactId>groovy</artifactId>
  <version>${groovy.version}</version>
</dependency>

Evaluate Groovy scripts

Evaluate from script text

GroovyShell groovyShell = new GroovyShell();
Object result = groovyShell.evaluate("return 'Hello World !'");
 
// print result to the console :
System.out.println(result);
// $> "Hello World !"

Evaluate from File

Let’s deal with the following file :

return 'Hello World !'

Now back to java :

GroovyShell groovyShell = new GroovyShell();
Object result = groovyShell.evaluate(new File("myfile.groovy");
 
// print result to the console :
System.out.println(result);
// $> "Hello World !"

Evaluate from classpath

Let’s deal with the following file in your classpath :

return 'Hello World !'

Now back to java :

// get reader from classpath :
InputStream in = this.getClass().getResourceAsStream("/myfile.groovy");
Reader reader = new InputStreamReader(in);
 
// evaluate reader :
GroovyShell groovyShell = new GroovyShell();
Object result = groovyShell.evaluate(reader);
 
// print result to the console :
System.out.println(result);
// $> "Hello World !"

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.