环境搭建
- 到官网下载
- 配置好环境到path
Intellij
- 用Intellij开发goory,因为已经内部集成了
- 新建-groovy-第一次新建需要选择groovy的路径
goovvyBean
- 新建一个grovvy class 名字book
class Book {
String title
}
- 看看调用set get
def groovyBook = new Book()
groovyBook.setTitle("hello word")
println(groovyBook.getTitle())
GString
字符串中的占位符,并能自动解析
def nick = "shark"
def book = "groovy in action"
println("$nick is $book")
数字也是对象
groovy中所有数字都是对象,不像java中有专用类型,groovy自动装箱和拆箱
def x = 2
println(x.toString().length())
range
groovy独有的,可以叫它范围,和for类似
def x = 1..10
x.each {
println("$it")
}
闭包
def str = ''
(9..5).each{element->
str+=element
}
println(str)
结构控制
package groovy
//if-else
if (1 > 2) {
println("真")
} else {
println("假")
}
// while
def i = 0
while (i < 5) {
println("while"+i)
i ++
}
// 迭代range
def result = 0
def rangers = 0..9
for (item in rangers) {
result += item
}
println("迭代range="+result)
// 迭代list
def list = [1, 2, 3, 4, 5]
for (item in list) {
println("迭代list="+item)
}
//switch
def key = 5
switch (key) {
case 1: println("good"); break
case 2: println("bad"); break
default: println("haha")
}
新建groovy class和java class区别
- 如果groovy class中包含了main方法,和java class一样
- 如果groovy class中,不包含main方法,就是groovy文件
网友评论