I have a simple java class:
package test;
class Hello {
public static void main(String[] args) {
System.out.println("Hi");
}
}
on which I do a
javac Hello.java
Problem: Now I would like to access this class from a groovy script (access.groovy) ...
import test.*
Hello.main(null)
but
groovy -cp . access.groovy
will result in a MissingPropertyException
. What am I doing wrong?
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.
Yes, you may intermix Java and Groovy sources in a project and have source dependencies in either direction, including "extends" and "implements".
A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class.
Your class Hello
needs to be declared as public to be accessible from other packages. As a dynamic language, Groovy can't identify such errors and ends up looking for a variable named Hello
.
It's generally a bad idea to use wildcard imports; in this case, using import test.Hello;
would have given you a better error message.
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