groovy
轻量级的简洁高效的面向对象的动态语言
- 支持动态修改语言特性
- 类型自动拆箱装箱,安全操作符,自动位空判断等
- 基于jdk 与java无缝结合
- api 简单有趣,易于掌握
class 使用
- 1.默认生成所有的变量的get , set方法,并且对于成员变量的访问会自动调用get set方法
- 2.private不能限制变量访问
- 3.方法重载
class c1{
def name;
def age;
c1(){
}
void setName(i){
this.name = i;
println "setName:$name"
}
void setAge(i){
this.age = i;
println "setName:$age"
}
void execute(x=10 , y=20 , z){
println "$x--$y--$z"
}
}
def cObject = new c1()
//此处的@name代表直接使用,不调用set方法
cObject.@name = "1234"
println cObject.name
//此处会自动调用set方法
cObject.name = "4567"
println cObject.name
cObject.execute(10)
cObject.execute(20 , 40)
cObject.execute(20 ,30, 40)
元编程
//meta test
String.metaClass.appendEnd{
delegate+"-end"
}
def a = "ssss";
println a.appendEnd()
闭包
- 1.闭包可以作为参数传递
- 2.闭包得参数类似与方法,可以有默认参数
- 3.闭包默认有个参数叫 it
- 4.闭包的参数通过->指定
def closure={
println it
}
//2.默认参数个数由->来指定
//3.闭包可以指定默认参数
// 4.闭包可以作为方法参数
def closure2={
a=10,b=20,c->
println "$a--$b--$c"
}
def testClosure(input ,closure2){
println "test -" + closure2(input)
}
closure("aaaaaa")
closure2(1,2,3)
testClosure(5){
return "$it"
}
与系统进程通信
println "pwd".execute().text
mop 元编程
注入
metaClass
class Test{
}
def test = new Test()
test.metaClass.testFunc = {
println "inject method"
}
test.testFunc()
替换方法
class Test{
def func(){
println "func called "
}
}
def test = new Test()
test.metaClass.func = {
println "repace func called "
}
test.func()
动态代理
metaClass.invokeMethod
class Test{
def func(){
println "func called "
}
}
Test.metaClass.invokeMethod = {String method , Object args->
println "brefore func called "
delegate.class.metaClass.getMetaMethod(method, args)?.invoke(delegate, args)
}
def test = new Test()
test.func()