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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With