Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top