本文整理自网络,侵删。
为了了解 Groovy 的基本语法,让我们先看看一个简单的 Hello World 程序。
创建你的第一个 Hello World 程序
创建Hello World程序,你只要输入以下几行简单的代码就可实现 -
class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } }
当我们运行上面的程序,我们会得到以下结果 -
Hello World
在 Groovy 中导入语句
import 语句可以用来导入,可以让你的代码使用其他库的功能。这是通过使用在 Import 关键字完成。
下面的示例演示了如何使用 MarkupBuilder 的类,它可能是最常用的创建 HTML 或 XML 标记的类之一。
import groovy.xml.MarkupBuilder def xml = new MarkupBuilder()
默认情况下,Groovy 在代码中包括以下库,因此您不需要显式导入它们。
import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal
Groovy 令牌
令牌可以是一个关键字,一个标识符,常量,字符串文字或符号。
println(“Hello World”);
在上面的代码行中,有两个令牌,首先是关键词的 println 而接下来就是字符串的“Hello World”。
Groovy 评论
在您的代码中使用注释。Groovy 的注释可以是单行或多行。
单行注释使用 // 在该行的任何位置来识别。一个例子如下所示 -
class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } }
多行注释标识与在开始 / * 和 * / 识别多行注释的末尾。
class Example { static void main(String[] args) { /* This program is the first program This program shows how to display hello world */ println('Hello World'); } }
分号
就像 Java 编程语言,它需要具有分号在 Groovy 定义多个语句之间进行区分。
class Example { static void main(String[] args) { // One can see the use of a semi-colon after each statement def x = 5; println('Hello World'); } }
上述例子示出了分号使用了不同行的代码语句之间进行区分。
身份标识
标识符被用来定义变量,函数或其他用户定义的变量。标识符以字母开头,美元或下划线。他们不能以数字开头。以下是有效标识符的一些例子
def employeename def student1 def student_name
其中,DEF 是在 Groovy 用来定义标识符的关键字。
相关阅读 >>
更多相关阅读请进入《Groovy》频道 >>

深入理解Java虚拟机 JVM高级特性与实践 周志明 第3版
这是一部从工作原理和工程实践两个维度深入剖析JVM的著作,是计算机领域公认的经典。