Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Groovy scripts as Java, from the command line?

Tags:

java

groovy

I'm trying to use groovyc, but something is not right:

>echo println("Hello world") > test.groovy
>groovy test.groovy
Hello world
>groovyc test.groovy
>java -cp C:\utils\groovy-1.8.1\embeddable\groovy-all-1.8.1.jar test
Error: Could not find or load main class test

>dir test.class
...

11/10/2011  02:54 PM             7,104 test.class

What am I missing?

like image 424
ripper234 Avatar asked Nov 10 '11 12:11

ripper234


People also ask

Can we run Java code in Groovy?

Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.


2 Answers

When you specify the classpath with -cp switch, its default value (current directory) is overwritten and so JVM can't find your class.

Add current directory to classpath, and everything works:

>java -cp C:\utils\groovy-1.8.1\embeddable\groovy-all-1.8.1.jar;. test
Hello, world
like image 104
socha23 Avatar answered Oct 29 '22 01:10

socha23


Make sure that if you are using a unix based system (Linux or Mac), then you need colon instead of semicolon for classpath entry separator:

>java -cp /path/to/groovy/embeddable/groovy-all-1.8.1.jar:. test
Hello, world
like image 37
Aston Avatar answered Oct 29 '22 03:10

Aston