1.Groovy开发环境配置
- 研发工具:Intellij IEDA
地址:https://www.jetbrains.com/idea/download/
-
groovySDK配置
地址:https://groovy.apache.org/download.html
配置环境变量
GROOVY_HOME=\apache-groovy-sdk-3.3\groovy-3.3
PATH中加入 %GROOVY_HOME%\bin
验证是否配置成功:groovy -version
-
在Intellij中配置groovy
File->Settings->找到Plugins->安装Groovy插件
2.变量与字符串
//弱类型的 使用def 就可以方便定义 必须要赋值才行 弱类型 可以自动转型
def a=10
def b='c'
def c=909.22
def d=true
//字符串
//单引号
name='lpf'
//双引号
a="bbbb ${name}" //可以引入变量的值 双引号还可以做计算
println(a)
println(a.class)
//三引号 原始格式输出
a='''cccc
ddd'''
//字符串可以直接比较大小
str1="test"
str2="Test"
println str1>str2
println("------------------")
//字符串的截取
println(str1[1..2])
//字符串可以直接进行减法操作
str1="test"
str2="st"
println("------------------")
println(str1 - str2)
//逆序操作
str3="1234"
println("------------------")
println(str3.reverse())
//首字母大写
str4="lpf"
println("-----------")
println(str4.capitalize())
3.闭包语法与基本使用
匿名内联函数,也称为一个闭包。本质上,闭包是将函数内部和函数外部连接起来的桥梁。
//匿名内联函数 无参数
def closure={
println("closure------")
}
//两种调用方式
closure()
closure.call()
带默认参数的
def closure={
println("closure------${it}")
}
//两种调用方式
closure.call("恬希")
//带参数的闭包 参数类型 可以省略
def closure={
name, age->
println("closure name is ${name} age is ${age}")
}
//两种调用方式
closure("恬希",1)
closure.call("恬希",1)
//带返回值 返回值不需要定义
def closure={
name, age->
println("closure name is ${name} age is ${age}")
return 123
}
//匿名内联函数 也称为闭包
int x=fab(5)
int fab(int number){
int result=1
1.upto(number,{
num->result*=num})
return result
}
println(x)
int fab(int number){
int result=1
number.downto(1){
result*=it
}
return result
}
println(fab(5))
int sum(int number){
int result=0
number.times {
result+=it //这部分就是一个闭包 很想lambda表达式
}
return result
}
println(sum(5))
str="2 add 3 is 5"
str.each {
print(it * 2) //每一个都复制出两个来
}
查找第一个数字的
str="2 add 3 is 5"
println str.find {
it.isNumber() //每一个都复制出两个来
}
查找所有 符合条件的字符
str="2 add 3 is 5"
print str.findAll {
it.isNumber()
}
//输出是:[2, 3, 5]
查找是否有符合条件的字符
str="2 add 3 is 5"
print str.any {
it.isNumber()
}
collect 遍历所有的元素 闭包当作一个参数 直接传入的
str="2 add 3 is 5"
print str.collect {
it.toUpperCase()
}
//输出 [2, , A, D, D, , 3, , I, S, , 5]
4.常用数据结构
-
List集合的声明 增删查改
//声明一个List集合 def list=[1,2,3,4,5] println(list.class) println(list.size()) //添加 list.add(6) list<<12 println(list.toString()) def newList=list+90 println(newList.toString()) //[1, 2, 3, 4, 5, 6, 12, 90] newList.add(2,34) println(newList.toString()) //删除 newList.remove(2) //下标删除 println(newList.toString()) newList.remove((Object)34) //删除对象 newList.removeElement(34) newList.removeAll{ return it%2!=0 //按照条件删除 } println(newList.toString()) println("---------------------") println newList-[2,4] //查找 println("------------") list=[1,-2,3,4,6,9] result=list.find{ it%2 ==0 } println(result) list=[1,-2,3,4,6,9] result=list.findAll{ it%2 ==0 } println(result) //any是指是否存在 list=[1,-2,3,4,6,9] result=list.any{ it%2 ==0 } println(result) //every 是否全部满足 list=[1,-2,3,4,6,9] result=list.every{ it%2 ==0 } println(result) //最小值 list=[1,-2,3,4,6,9] result=list.min{ Math.abs(it) } println(result) //最大值 list=[1,-2,3,4,6,9] result=list.max{ Math.abs(it) } println(result) //统计 list=[1,-2,3,4,6,9] result=list.count{ it>0 } println(result) println("-------------------------------------------") //排序 list=[1,-2,3,4,6,9] print list.sort() //默认从小到大 println() println("-------------------------------------------") print list.sort{ a,b-> a==b?0:a<b?1:-1 //按照条件排序 } println() list=["aaaa","bb","dddddd","ee","f"] print list.sort{ it.size() } println()
-
Map 声明和遍历
colors=[red:'red111',green:'green222',blue:'blue333'] println(colors.red) //如果是.class 会当成一个键 println(colors.getClass()) colors.yellow='yellow444' println(colors) colors.map=[a:'a111',b:'b222'] println(colors) colors.each { println(it.key+"-----"+it.value) }
-
range 声明 取值 判断是否包含
//声明一个range range=1..10 //rangge的取值 println(range[2]) //range判断是否包含 println(range.contains(8))
5.JSON与XML解析
对象转json json转对象
json=[new Person(name: "tom",age: 20),new Person(name: "andy",age: 21)]
println(JsonOutput.toJson(json))
json=JsonOutput.toJson(json)
//对象转json 格式化输出
println(JsonOutput.prettyPrint(json))
println("----------------------------")
//json 转对象
jsonSluper=new JsonSlurper()
def result = jsonSluper.parse("[{\"name\":\"tom\",\"age\":20},{\"name\":\"andy\",\"age\":21}]".bytes)
println(result.class)
println(result)
xml 数据解析里边的各个字段
final String xmlStr='''<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.meishe.plugincollection">
<test>123</test>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.PluginCollection">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>'''
def xmlSlurper=new XmlSlurper()
//解析xml类型的字符串
//result=xmlSlurper.parseText(xmlStr)
//解析文件中的数据
result=xmlSlurper.parse("./AndroidManifest.xml")
println(result.@package)
println(result.test.text())
//读取有域名控件的节点
result.declareNamespace('android':'http://schemas.android.com/apk/res/android')
println(result.application.@'android:allowBackup')
println(result.application.activity[0].@'android:name')
//读取intent-filter 下面的数据 注意因为有-符号,所以需要加引号
println("action----"+result.application.activity[0]."intent-filter".action.@'android:name')
println("category----"+result.application.activity[0]."intent-filter".category.@'android:name')
println("--------------------------------------")
result.application.activity.each{
//遍历获取
println(it.@'android:name')
}
生成xml类型的数据,
def stringWrite = new StringWriter()
def xmlBuilder = new MarkupBuilder(stringWrite)
xmlBuilder.html(){
title(id:'groovy',name:'android','testXmlBuilder'){
android()
}
body(name:'groovy'){
activity(serviceName:'service1',class:'DownloadService','server')
activity(serviceName:'service2',class:'SearchService','server')
}
}
println stringWrite
/**
* 生成XML格式数据
* <html>
* <title id='groovy',name='android'> testXmlBuilder
* <android></android>
* </title>
* <body name='groovy'>
* <service serviceName='service1' class='DownloadService'>server</service>
* <service serviceName='service2' class='SearchService'>server</activity>
* </body>
* </html>
*/
6.文件操作
def file = new File("F:\\java_project\\groovy\\GroovyCollection\\src\\jsonAndXml\\AndroidManifest.xml")
//遍历文件 一行一行的读取
file.eachLine {
line->
println line
}
//返回所有文本 一次性返回所有的
def text = file.getText()
println text
//以List<String>返回文件的每一行
def text = file.readLines()
println text.toListString()
//以java中流的方式读取文件内容
def reader = file.withReader {
reader->
char [] buffer = new char[1024]
reader.read(buffer)
return buffer
}
println reader