
groovy中的接口
interface Action {
void eat()
void play()
}
trait DefaultAction {
abstract void eat()
void play() {
println "i can play"
}
}
接下来有类实现接口
class Student implements DefaultAction{
String name
Integer age
@Override
void eat() {
}
}
//groovy默认都是public
//用.属性也是相当于用get
Student.metaClass.sex = 'male' //动态添加属性
def stu = new Student(name: "jimmy", age: 31)
println "name: ${stu.getName()}, age: ${stu.age}"
stu.play()
println stu.sex
println stu.cry() //不存在的方法 在运行时才会报错
运行结果如下
name: jimmy, age: 31
i can play
male
Caught: groovy.lang.MissingMethodException: No signature of method: com.cjt.groovy.objectorention.Student.cry() is applicable for argument types: () values: []
Possible solutions: any(), any(groovy.lang.Closure), eat(), play(), grep(), every()
groovy.lang.MissingMethodException: No signature of method: com.cjt.groovy.objectorention.Student.cry() is applicable for argument types: () values: []
Possible solutions: any(), any(groovy.lang.Closure), eat(), play(), grep(), every()
at com.cjt.groovy.objectorention.studenttest.run(studenttest.groovy:10)
接下来,换个类看个例子(暂不实现接口)
重写 invokeMethod , methodMissing
在类实例中调用不存在的方法时会调用此方法,存在优先级别
class People {
String name
Integer age
def increaseAge(Integer years) {
this.name += years
}
//重写此方法, 若调用此类没有的方法,编译时不报错, 执行时会执行此方法
def invokeMethod(String name, Object args)
{
return "this method is ${name}, agrs: ${args}"
}
def methodMissing(String name, Object args)
{
return "this method ${name} is missing"
}
}
//groovy默认都是public
//用.属性也是相当于用get
People.metaClass.sex = 'male' //动态添加属性
def people = new People(name: "jimmy", age: 31)
println "name: ${people.getName()}, age: ${people.age}"
people.play()
println people.cry() //不存在的方法 在运行时才会报错
println people.sex
println "------为类动态添加方法-----------"
People.metaClass.setUpperCase = { -> sex.toUpperCase() }
def p = new People(name: "吉米", age: 22)
println p.setUpperCase()
println "------为类动态添加静态方法-----------"
People.metaClass.static.createPeople = {
String name, int age -> new People(name: name, age: age)
}
def p2 = People.createPeople("cjt", 25)
println "name: " + p2.name +" , age: " + p2.age
结果如下
name: jimmy, age: 31
this method cry is missing
male
-----------------
MALE
------为类动态添加静态方法-----------
name: cjt , age: 25
外部注入类方法,在整个应用中有效

/**
* 模拟一个应用的管理类
*/
class ApplicationManager {
static void init() {
ExpandoMetaClass.enableGlobally()
//为第三方类添加方法
People.metaClass.static.createPeople = {
String name, int age -> new People(name: name, age: age)
}
}
}
class PeopleManager {
static People createPeople(String name, int age) {
return People.createPeople(name, age)
}
}
//外部注入类方法,在整个应用中有效
class Entry {
static void main(def args) {
println '应用程序正在启动...'
//初始化
ApplicationManager.init()
println '应用程序初始化完成...'
def p = PeopleManager.createPeople("吉米", 28)
println "create people name: ${p.name}, age: ${p.age}"
}
}
输出结果 :
应用程序正在启动...
应用程序初始化完成...
create people name: 吉米, age: 28
网友评论