groovysh Starts the groovysh command-line shell, which is used to execute Groovy code
interactively. By entering statements or whole scripts, line by line, into the shell and
giving the go command, code is executed “on the fly.”
groovyConsole Starts a graphical interface that is used to execute Groovy code interactively; moreover,
groovyConsole loads and runs Groovy script files.
groovy Starts the interpreter that executes Groovy scripts. Single-line Groovy scripts can be
specified as command-line arguments.
让我们先来看一下groovysh,他是用来执行Groovy程序的.在这个shell里面很容易编辑和执行Groovy,可以不用创建脚本文件,
================
Version: 1.0-RC-01-SNAPSHOT JVM: 1.4.2_05-b04
Type 'exit' to terminate the shell
Type 'help' for command help
Type 'go' to execute the statements
groovy>
groovy> go
===> Hello, World!
groovy> "${greeting}, World!"
groovy> go
===> Hello, World!
groovy> binding
Available variables in the current binding
greeting = Hello
使用groovy:
groovy命令被用来执行代码和脚本,例如以下代码.用来打印十个数字.每个数字都是前面两个数字的和,
current = 1
next = 1
10.times {
print current + ' '
newCurrent = next
next = next + current
current = newCurrent
}
println ''
加入你想执行这段代码,保存该代码到test.groovy文件,要保持为groovy后缀,groovy脚本段程序也要保持到.groovy文件里.这样做的一个好处就是你在groovy命令行里面可以不用键入后缀名就可以执行.
程序得到结果为:
> groovy test
1 1 2 3 5 8 13 21 34 55
groovy还有一些额外参数.比如groovy –e "println 1+1" 就可以得到2.以后将会对这些有更详细的讲述.
到目前为止,我们介绍了直接在groovy里面运行groovy代码的直接模式,另一方面我们还有另外一种被要做预编译模式.groovyc编译.groovy文件,对每个Groovy文件也至少产生一个.class文件,再有JVM执行.两种模式区别就是,前者在内存里面执行,而后者被存储到硬盘里.
第二种模式:> groovyc –d classes test.groovy
我们加了-d参数,这样会产生两个.class文件.假如没有-d,.class文件会被建立,当你运行这个编译的时候,生成的.class文件的名字会被打印到控制台上.是否有多个class文件生成,取决于文件里的脚本代码,然而,我们不必关心这个,因为那是java虚拟机的事情.