Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a Groovy class in a package from the command line

Is there a way to execute a Groovy class by specifying the package with dots, as with java?

Example: File ./my/package/MyClass.groovy:

package my.package

class MyClass {
  static void main(String[] args) {
    println "ok"
  }
}
> cd my/package
my/package> groovy MyClass
ok
> cd ../..
> groovy my/package/MyClass.groovy
ok
> groovy my/package/MyClass
ok
> groovy my.package.MyClass
Caught: java.io.FileNotFoundException: my.package.MyClass

I was expecting the last command to work. I tried various ways of setting the classpath, to no avail.

like image 365
Olivier Gourment Avatar asked May 28 '09 03:05

Olivier Gourment


People also ask

How do you call a class in Groovy?

In Groovy we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.

How do I compile a Groovy script?

For most Groovy scripts I use, I simply run the script from its Groovy source code as-is and allow the compilation to take place implicitly. However, it can be helpful at times to use groovyc to compile Groovy code into . class files and then execute those . class files via the normal Java launcher (java).


1 Answers

First of all, package is a reserved keyword, so you can't use it as a a package name.

Second of all, you can't do that in Groovy, since the dot notation is used for classes, not for scripts, so you need a compiled class file to use it.

Still, you can replace the groovy command with java + classpath:

java -cp /usr/share/java/groovy/embeddable/groovy-all-1.6.3.jar:. my.some.MyClass

You can add an alias to it 'g_java' for instance to make it less verbose.

like image 126
Robert Munteanu Avatar answered Sep 30 '22 11:09

Robert Munteanu