Today we are going to see on Using Groovy Compiler – groovyc to execute Groovy class files. One of the ways you can execute the Groovy files is by writing the Groovy code in a “.groovy” file and then executing the groovyc command on the Groovy file which will compile the Groovy code and creates a “.class” file.
The groovyc compiles the Groovy code into byte code.
Lets take the following simple Groovy class code and save it in a file called as “Person.groovy”:
class Person { def sayHello() { println "Hello there" } }
Lets create another Groovy file named as App.groovy and paste in the following content in the file:
Person p = new Person() p.sayHello()
Now open up the terminal and navigate to the directory in which these Groovy files are located and here we are going to compile these Groovy files into class files containing the byte code. You can either compile one file at a time using the following command:
groovyc Person.groovy
Or you can compile all the Groovy files using a single command:
groovyc *.groovy
Once you have executed the groovyc command, you can notice that it created class files “Person.class” and “App.class”. These are class files that Groovy compiler created and if you open up these files to view the contents it will be full of byte codes.
Now to view the output of these class files, execute the following command on the App file because it is in the App file we are creating the object and calling the sayHello method that prints the output.
groovy App
This will produce the output: