前置环境
JDK的安装以及其环境配置
相关SDK
安装groovy SDK
使用homebrew安装groovy
brew install groovy
查看一下已经安装的groovy的版本
luogw@luogw-MacBook-Pro notes$ groovy --version
Groovy Version: 2.5.0 JVM: 1.8.0_172 Vendor: Oracle Corporation OS: Mac OS X
命令行的环境
写groovy脚本(文件后缀名为groovy),直接使用groovy命令运行脚本文件即可
groovy的使用帮助如下所示:
luogw@luogw-MacBook-Pro notes$ groovy -h
Usage: groovy [options] [filename] [args]
The Groovy command line processor.
-cp, -classpath, --classpath=<path>
Specify where to find the class files - must be first
argument
-D, --define=<property=value>
Define a system property
--disableopt=optlist[,optlist...]
Disables one or all optimization elements; optlist can
be a comma separated list with the elements:
all (disables all optimizations),
int (disable any int based optimizations)
-d, --debug Debug mode will print out full stack traces
-c, --encoding=<charset> Specify the encoding of the files
-e= <script> Specify a command line script
-i= [<extension>] Modify files in place; create backup if extension is
given (e.g. '.bak')
-n Process files line by line using implicit 'line'
variable
-p Process files line by line and print result (see also
-n)
-pa, --parameters Generate metadata for reflection on method parameter
names (jdk8+ only)
-l= [<port>] Listen on a port and process inbound lines (default:
1960)
-a, --autosplit[=<splitPattern>]
Split lines using splitPattern (default '\s') using
implicit 'split' variable
--indy Enables compilation using invokedynamic
--configscript=<script>
A script for tweaking the configuration options
-b, --basescript=<class> Base class name for scripts (must derive from Script)
-h, --help Show this help message and exit
-v, --version Print version information and exit
直接运行脚本
示例如下:
luogw@luogw-MacBook-Pro temp$ groovy -e 'println "Hello World!"'
Hello World!
运行脚本文件
新建demo.groovy文件,文件中写入 println “Hello World!”,操作示例如下
luogw@luogw-MacBook-Pro temp$ touch demo.groovy && echo 'println "Hello World!"'>demo.groovy
luogw@luogw-MacBook-Pro temp$ cat demo.groovy
println "Hello World!"
luogw@luogw-MacBook-Pro temp$ groovy demo.groovy
Hello World!
IDE的开发环境
IDEA的开发环境
由于IDEA创建groovy工程时,配置groovy library的路径时选择不了/usr/local/Cellar/groovy/2.5.0,所以这里额外下载一分groovy的sdk并解压到~/dev_tool/groovy-2.5.0
创建工程
编码运行
1.创建groovy源文件,在src目录右键菜单新建一个groovy类文件,文件名为HelloGroovy
2.编写main方法,HelloGroovy的内容如下
class HelloGroovy {
static void main(args) {
println("Hello, Groovy")
}
}
3.编译与运行,在新建类文件上右键菜单,然后Run “xxx.main”
运行结果如下,注:运行第一次以后,后续可以直接点击绿色的三角运行按钮编译与运行