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
变量定义
两种方式定义 - 使用数据类型的本地语法,或者使用def关键字
同一作用域变量不能重复定义
-
def a = 10;
-
int a = 10
运算符
- 算数运算符: +,-,*,/,%(取余数),++,–
- 关系运算符:>,<,>=,<=,!=,==
- 逻辑运算符:&&,||,!
- 位运算符:&,|,~(取反),^(异或),<<(左移动),>>(右移)
循环
- while
def count = 0
while (count < 5) {
println(count)
count ++
}
- for
for(i=0;i<6;i++){
println(i)
}
- for-in
for (i in [0,1,2,3]){
println(i)
}
条件
- if-else
a = 11;
if (a < 9) {
println("This value less than 9")
}
else {
if (a > 10){
println("This value more than 10")
}
else {
println("This value equal to 10")
}
}
- switch
a = 3
b = 3
switch(a){
case 1:
println(1)
break
case 2:
println(2)
break
case 3:
println(3)
switch(b){
case 1:
println("this is 1")
break
default:
println("default")
}
break
default:
println("nested default case!!");
}
方法
- def 关键字
def test(){
println("test")
}
- 返回类型
void test(){
println("test")
}
####### 方法参数
- 位置
def sum(Integer[] args){
return args[0] + args[1]
}
c = sum(1,3)
println(c)
- 关键字
def sum(a, b){
return a +b
}
c = sum(a=1,b=5)
c = sum(b=1,a=5)
println(c)
- 默认值
def sum(a, b=10){
return a +b
}
c = sum(a=1,b=5)
c = sum(a=1)
println(c)
- 定义参数数据类型
def test(a){
print(a)
}
test('1')
def test(int a){
print(a)
}
test('1')
/* groovy.lang.MissingMethodException: No signature of method: test.test() is applicable for argument types: (String) values: [1]
Possible solutions: test(int), getAt(java.lang.String), wait(), use([Ljava.lang.Object;), wait(long), is(java.lang.Object) */
- 修饰符
| | | | | |
| ---- | ---- | ---- | ---- | ---- |
|修饰符|同类|子类|同包|其他包|
|public| √| √| √| √|
|protected| √| √| √| ×|
|private| √| ×| ×| ×|
指定序列
1…10 - 包含范围的示例
1 … <10 - 独占范围的示例(不包含10)
‘a’…‘x’ - 范围也可以由字符组成
10…1 - 范围也可以按降序排列
‘x’…‘a’ - 范围也可以由字符组成并按降序排列。
def rint = 0..10
for (i in rint){
println(i)
}
list
def rint = [1,2,3]
a[1]
a[1..2]
a[-2..-1]
a.find{it > 4}
a.findAll{it > 4}
映射
映射(也称为关联数组,字典,表和散列)是对象引用的无序集合。
[key:value, key:value]
[:] 空映射
def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"];
mp.containsKey("TopicName1")
// 键可以重复,删除旧值
def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps", "TopicName": "1"];
mp.containsKey("TopicName")
mp.get("TopicName") // 1,重复取最新的值
// 键集合
mp.keySet()
// 值集合
mp.values()
// 更新
mp.put("TopicID","1")
//大小
mp.size()
正则表达
符号为 =~, 右侧为正则表达式
groovy> if ('abc' =~ '^a') {
groovy> println('true')
groovy> }
groovy> if ('^a' =~ 'abc') {
groovy> println('true')
groovy> }
true
异常处理
def hello() {
try {
int a = "";
println("yes")
}
catch (Exception Ex) {
println("")
}
finally {
println("final")
}
}
hello()