Groovy 语法学习
基本语法学习
定义变量
一切基本类型都是对象
int x = 10
println x.class
double y = 3.123
println y.class
使用def定义变量
该方式定义变量可以不声明变量的类型
def a = 123;
println a.class
def b = "yaoyan"
println b.class
会自动转换成相应的对象
String类型声明
‘单引号声明’
def a = '123'
println a.class
println a
“双引号声明”
双引号声明可以对字符串进行扩展
def c = "heihei"
println c.class
def d = "123 ${c}"
println d
println d.class
返回的类型是GStringImpl
‘’‘三引号声明’’’
def b = '''ascsd
123
4214
'''
println b
println b.class
三引号声明当拼接字符串时可以省略 + 号
遍历
遍历范围
def sum = 0
for(i in 0..5) {
sum += i;
}
println sum
遍历数组
sum = 0
for (i in [0, 1, 2, 3, 4, 5, 6]) {
sum += i
}
println sum
遍历Map
for (i in ["name": 'zhang', "address": "shenyang"]) {
println i.key
println i.value
}
闭包
有参数、返回值
def result = {
String name,
int age
->
println "name: ${name}, age: ${age}"
}
def returnResult = {
String name,
int age
->
return "name: ${name}, age: ${age}"
}
result("yaoyan", 25)
println returnResult("yaoyan", 25)
It参数
def resultIt = {
println("address: ${it}")
}
it代表传递的参数
当调用一个方法时
求一个数的阶乘
public static void test2(int current, Closure closure) {
for (int i = 1; i <= current; i++) {
closure.call(i);
}
}
把闭包写在()里面
int test3(int current) {
int result = 1;
test2(current, {num -> result *= num})
return result;
}
把闭包写在()外面
int test3(int current) {
int result = 1;
test2(current) {
num -> result *= num
}
return result;
}
都可以打印120
构造函数传值
class Student {
String name
def printName = {println "my name is ${name}"}
}
def student = new Student(name: "yaoyan")
student.printName.call()
集合学习
List
定义List
方式一
def list = [0, 1, 2, 3] as ArrayList
println list.class
方式二
def list = [0, 1, 2, 3] as LinkedList
println list.class
排序
方式一
def array = [5, 4, 3, 2, 1, 0]
array.sort {
a, b ->
a == b ? 0 : a < b ? -1 : 1
}
println array
方式二
def nums = [-2, -1, 0, 1, 2] as ArrayList
def mc = {
Integer num1, Integer num2 ->
num1 == num2 ? 0 : num1 > num2 ? -1 : 1
}
Collections.sort(nums, mc)
println nums
列表遍历
def lists = [0, 1, 2, 3]
lists.each { it ->
println it
}
列表查找
查找第一个为偶数的数字
def nums = [-3, -1, 0, 1, 2] as ArrayList
def n = nums.find() {
it ->
it % 2 == 0
}
println n
查找所有为偶数的数字
def nums = [-3, -1, 0, 1, 2] as ArrayList
def n = nums.findAll {
it ->
it % 2 == 0
}
println n
查找数组里面是否包含偶数
def nums = [-3, -1, 0, 1, 2] as ArrayList
def n = nums.any {
it ->
it % 2 == 0
}
println n
查找数组里是否全部为偶数
def nums = [-4, -2, 0, 8, 2] as ArrayList
def n = nums.every {
it ->
it % 2 == 0
}
println n
数组
方式一
def array = [0, 1, 2, 3] as int[]
方式二
int[] array2 = [0, 1, 2, 3]
Map
定义
def map = new HashMap()
def students = [
name: 'yaoyan',
id: '1123123',
address: 'beijing'
]
通过索引查找
def students = [
name: 'yaoyan',
id: '1123123',
address: 'beijing'
]
println students['name']
println students.id
添加元素
添加同类型元素
// 添加元素
students.favorite = 'football'
println students.favorite
添加不同类型元素
// 添加多个不同类型的元素
students.other = [
age: 25,
marry: false
]
println students.other
遍历
使用对象遍历
def students = [
1: [name: 'yaoyan',
id: '1123123',
address: 'beijing',
score: 60,
sex: 'male'],
2: [name: 'xiaozhang',
id: '4235',
address: 'shenzhen',
score: 70,
sex: 'male'],
3: [name: 'xiaoli',
id: '42343',
address: 'guangzhou',
score: 80,
sex: 'feMale'],
4: [name: 'xiaowang',
id: '4545',
address: 'shanghai',
score: 90,
sex: 'feMale'],
5: [name: 'xiaohong',
id: '345',
address: 'shenyang',
score: 99,
sex: 'feMale']
]
带索引遍历
students.eachWithIndex { def student, int index ->
println "key = ${student.key}, value = ${student.value}, index = ${index}"
}
key、valueb遍历
方式一
students.each { key, value ->
println "key = ${key}, value = ${value}"
}
方式二
students.eachWithIndex{ key, value, index ->
println "key = ${key}, value = ${value}, index = ${index}"
}
查找
find
def find = students.find { student ->
student.value.score > 80
}
findAll
def findAll = students.findAll { student ->
student.value.score > 80
}
统计个数
def count = students.count { student ->
student.value.score >= 60 && student.value.sex == 'male'
}
println count
collect使用
def collect = students.findAll { student ->
student.value.score > 80
}.collect { key, value ->
value.name
}
println collect
分组
def by = students.groupBy { student ->
student.value.score >= 60 ? '及格' : '不及格'
}
println by
排序
def sort = students.sort { student1, student2 ->
def a = student1.value.score
def b = student2.value.score
a == b ? 0 : a < b ? 1 : -1
}
println sort
范围
定义
def a = 0..10
查找
println a[5]
判断是否存在
println a.contains(7)
面向对象学习
trait
对象调用流程
当对象调用的方法不存在时,会调用对象的invokeMethod方法
class Person {
String name
Integer age
@Override
Object invokeMethod(String s, Object o) {
return "invokeMethod: method = ${s}, arguments = ${o}"
}
}
def person = new Person()
println person.test()
当invokeMethod方法存在,并且methodMissing方法也存在,就会只调用methodMissing方法
class Person {
String name
Integer age
@Override
Object invokeMethod(String s, Object o) {
return "invokeMethod: method = ${s}, arguments = ${o}"
}
def methodMissing(String name, def args) {
return "methodMissing: method = ${name}, arguments = ${args}"
}
}
动态添加对象属性、方法、静态方法
动态添加属性
Person.metaClass.sex = 'male'
def person = new Person(name: 'yaoyan', age: 25)
println person.sex
person.sex = 'Female'
println person.sex
动态添加方法
Person.metaClass.sex = 'male'
def person = new Person(name: 'yaoyan', age: 25)
println person.sex
person.sex = 'Female'
println person.sex
Person.metaClass.setUpperCase = { ->
sex.toUpperCase()
}
def person2 = new Person(name: 'yaoyan', age: 25)
println person2.setUpperCase()
println person.setUpperCase()
添加静态方法
Person.metaClass.static.createPerson = { String name, int age ->
new Person(name: name, age: age)
}
def person = Person.createPerson("xixi", 26)
println "name = ${person.name}, age = ${person.age}"
enableGlobally
使metaClass全局使用,默认不可以。没有ExpandoMetaClass.enableGlobally()之前,动态添加的属性,方法,不能被别的地方使用
class ApplicationManager {
static void init() {
ExpandoMetaClass.enableGlobally()
Person.metaClass.static.createPerson = {
String name, int age ->
new Person(name: name, age: age)
}
}
}
class PersonManager {
static Person createPerson(String name, int age) {
return Person.createPerson(name, age)
}
}
class Person {
String name
Integer age
@Override
Object invokeMethod(String s, Object o) {
return "invokeMethod: method = ${s}, arguments = ${o}"
}
def methodMissing(String name, def args) {
return "methodMissing: method = ${name}, arguments = ${args}"
}
}
class Entry {
public static void main(String[] args) {
ApplicationManager.init()
def person = PersonManager.createPerson("yaoyan", 25)
println "name = ${person.name}, age = ${person.age}"
}
}
Json处理
将对象转换为json
def list = [
new Person(name: 'yaoyan', age: 25),
new Person(name: 'xieyaoyan', age: 28)
]
def json = JsonOutput.toJson(list)
println json
def print = JsonOutput.prettyPrint(json)
println print
将json转换为对象
import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
def text = slurper.parseText("[\n" +
" {\n" +
" \"age\": 25,\n" +
" \"name\": \"yaoyan\"\n" +
" },\n" +
" {\n" +
" \"age\": 28,\n" +
" \"name\": \"xieyaoyan\"\n" +
" }\n" +
"]")
def age = text[0].age
def name = text[0].name
def age1 = text[1].age
def name1 = text[1].name
println age
println name
println age1
println name1
文件处理
读取一行、多行、buffer
def file = new File("../StudyGroovy.iml")
file.each { String line ->
//println line
}
def text = file.getText()
// println text
def lines = file.readLines()
// println lines
def buffer = file.withReader { reader ->
char[] buffer = new char[40]
reader.read(buffer)
return buffer
}
println buffer
copy
def sourceFile = new File("../StudyGroovy.iml")
def detectionFile = new File("../StudyGroovy1.iml")
detectionFile.createNewFile()
sourceFile.withReader { reader ->
detectionFile.withWriter { write ->
def lines = reader.readLines();
lines.each { line ->
write.append(line)
write.append("\r\n")
}
}
}
对象写入与读取
def file = new File("../object.bin")
file.createNewFile()
def person = new Person(name: "yaoyan", age: 25)
file.withObjectOutputStream { out ->
out.writeObject(person)
}
def personCopy = null
file.withObjectInputStream { input ->
personCopy = (Person)input.readObject()
}
println "name : ${personCopy.name} age : ${personCopy.age}"