Groovy探索之invokeMethod方法
我们知道,在Java语言中,所有的java类都继承了Object对象。通过Object对象,所有的java类都隐藏的实现了“equals”等方法。同样,在Groovy语言中,所有的Groovy类都隐藏的实现了GroovyObject接口,这样,我们的Groovy类就隐藏的实现了很多的方法,如“isCase”等。
这篇文字要谈谈的就是GroovyObject接口的“
invokeMethod”方法,这个方法对于我们Groovy语言的动态性编程很有帮助,可以帮助我们实现一些很有时代性的功能,比如DSL。本文就是要谈谈“
invokeMethod”方法的基础,通过这个基础,我们才可以通向DSL编程。
class
InvokeMethodTestor {
def
test
()
{
println
'hello,function name is test'
}
def
invokeMethod(String name,Object args)
{
println
"the other function,name is ${name}"
}
}
在讲述“
invokeMethod”方法的作用之前,我们先来测试一下上面的类。
def
testor =
new
InvokeMethodTestor()
testor.
test
()
testor.hello()
testor.doSomething()
我们先来看看测试结果:
hello,function name is test
the other function,name is hello
the other function,name is doSomething
通过测试结果,我们可以看出,语句“
testor.
test
()
”调用了“
InvokeMethodTestor
”类的“
test
”方法,而语句“
testor.hello()
”和“
testor.doSomething()
”却都调用了“
InvokeMethodTestor
”类的“
invokeMethod
”方法。
这就告诉我们,对于一个实现了“
invokeMethod
”方法的
Groovy
类的对象,可以执行任意的方法,如果该方法已经在该类中实现,就调用该方法,如“
testor.
test
()
”就调用“
InvokeMethodTestor
”类的“
test
”方法;如果该方法没有在该类中实现,如“
testor.hello()
”和“
testor.doSomething()
”,就调用该类的“
invokeMethod
”方法。
下面试着举一个小小的例子说明。
class
Student {
String no;
String name;
}
List scores = [
new
Student(no:
'123'
,name:
'Tom'
,chinscore:
90
,mathscore:
99
,englscore:
60
,physscore:
88
,chemscore:
96
)]
scores<<
new
Student(no:
'124'
,name:
'Mike'
,chinscore:
88
,mathscore:
90
,englscore:
90
,physscore:
98
,chemscore:
87
)
scores<<
new
Student(no:
'125'
,name:
'Alice'
,chinscore:
100
,mathscore:
55
,englscore:
98
,physscore:
67
,chemscore:
56
)
这些学生在
List
对象里是以学号排序的,我们来看看:
println
it.name+
' : '
+it.no
}
结果为:
Tom : 123
Mike : 124
Alice : 125
可以看到的确如此。
下面,我们的语文老师希望以语文成绩排序,而数学老婆希望以数学成绩排序,英语老师则希望以英语成绩排序,
……
,班主任则希望以总分排序。
这个方法当然是不错的,但不是最酷的。最酷的方法是语文老师调用
sortByChinscore
()方法,而数学老师调用
sortByMathscore
()方法,英语老师调用
sortByEnglscore
()方法,等等。
import
java.util.Collections
import
java.util.Comparator
class
SortHelper{
def
list
public
SortHelper(list)
{
this
.list = list
}
def
invokeMethod(String name,Object args)
{
if
(name.indexOf(
'sortBy'
)==
0
)
{
name = name[
6
..name.length()-
1
]
name = name[
0
].toLowerCase()+name[
1
..name.length()-
1
]
node1,node2 ->
//
排序
}
}
}
真的很简单。下面我们来测试一些这个类:
println
it.name
}
结果为:
Mike
Tom
Alice
从语文成绩来看,
Mike 88
,
Tom 90
,
Alice 100
。排序是正确的。下面我们以数学成绩排序:
println
it.name
}
结果为:
Alice
Mike
Tom
从数学成绩来看,
Alice 55
,
Mike 90
,
Tom 99
,排序也没有问题。大家可以再测几个看看。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。