views:

1248

answers:

1

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.

+4  A: 

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.

Robert Munteanu
It sounds like the right answer, but it isn't working. I used "my.package" as an example, by the way- a bad one I realize. Anyway, even with an acceptable package name, and after compilation with groovyc, it doesn't work. groovyc my/some/MyClass.groovy export CLASSPATH=. ls my/some/MyClass.class my/some/MyClass.class groovy my.some.MyClass Caught: java.io.FileNotFoundException: /Users/olivier/my.some.MyClass (/Users/olivier/my.some.MyClass)?
Olivier Gourment
You're right, I don't know how I missed that. If you don't mind cheating a bit, you can replace the groovy command with java + classpath:java -cp /usr/share/java/groovy/embeddable/groovy-all-1.6.3.jar:. my.some.MyClassYou can add an alias to it 'g_java' for instance to make it less verbose.
Robert Munteanu
Thanks. It works. So, the answer to my original question is: No, it doesn't work this way in Groovy. You have to use javac and java.
Olivier Gourment
Updated the question to reflect the correct answer.
Robert Munteanu
Thanks, I was looking for this answer. +1. Is there an extra period at the end of your java... line?
Yar
@yar: good catch, removed.
Robert Munteanu