groovyc, java -cp and Java side by side

groovy file.groovy compiles the script in memory and runs it. The compiler is also a command of its own: groovyc writes the .class files that javac would write, and the JVM runs them. A class file is what a build produces, what a jar holds, and what a Java program calls.

Compile a class

A class file holds the class of the same name. The path below is one class and its command:

groovyc Hello.groovy && ls && java -cp .:/opt/groovy/lib/groovy-5.0.8.jar Hello

Hello.class
Hello.groovy
Hello from a class file

groovyc wrote Hello.class and no other file. java needs the class file and the Groovy runtime jar: a Groovy class extends groovy.lang.GroovyObject, so the JVM cannot link it without groovy-5.0.8.jar. The distribution keeps that jar, and every other one, in $GROOVY_HOME/lib.

The same file runs without a compile step, because the launcher compiles it first:

groovy Hello.groovy

Hello from a class file

What the compiler writes for a script

A file with no class is still a class after the compile: the script body becomes run() of a class named after the file, and a main method is added to start it. That is why a script and a class are the same thing to the JVM, and why a script cannot be named like a class it declares.

groovyc Greeter.groovy && javap -classpath . Greeter

Compiled from "Greeter.groovy"
public class Greeter implements groovy.lang.GroovyObject {
  public static transient boolean __$stMC;
  public Greeter();
  public java.lang.String greet();
  protected groovy.lang.MetaClass $getStaticMetaClass();
  public groovy.lang.MetaClass getMetaClass();
  public void setMetaClass(groovy.lang.MetaClass);
  public java.lang.String getName();
  public void setName(java.lang.String);
}

javap lists the members the compiler generated: the constructor, the getter and the setter of name, and greet(). The property of a Groovy class is a private field with a public accessor pair, which the classes lesson takes apart.

Java calls a Groovy class

The two languages produce the same bytecode, so a Java class calls a Groovy one as if a Java compiler had written it. The Java source needs no import of anything Groovy:

groovyc Greeter.groovy && javac -cp .:/opt/groovy/lib/groovy-5.0.8.jar UseGreeter.java && java -cp .:/opt/groovy/lib/groovy-5.0.8.jar UseGreeter

Hello, Java, from Groovy

The first attempt, without the jar on the javac class path, fails with a message worth knowing:

groovyc Greeter.groovy && javac -cp . UseGreeter.java

UseGreeter.java:4: error: cannot access GroovyObject
        greeter.setName("Java");
  class file for groovy.lang.GroovyObject not found
1 error
exit status: 1

javac found Greeter.class and then needed the type of its superclass, GroovyObject, which lives in the Groovy jar. The fix is the same jar on the compile class path, as in the run above.

Related

Автор статьи: Arthur Isaev