Starting with groovy1.1beta-2, the ability to achieve dynamic change of objects is very simple:
In the beginning, we have such a class:
class Person {
String name
}
Instances of this class are dumb and unable to speak, as creator we should refine them so that they can introduce themselves (add instance methods):class Person {
String name
}
// 添加自我介绍的行为
Person.metaClass.introduce << {println "I'm $name"}
Now let's see if they can really talk about themselves:
class Person {
String name
}
// 添加自我介绍的行为
Person.metaClass.introduce << {println "I'm $name"}
def person = new Person(name:"山风小子")
person.introduce()
Run Result:
I ' m a mountain boy
Ah ~ The success of human transformation ~
But people should have sex, eh ~ Yes, plus the personality attribute sex (add attribute):
class Person {
String name
}
// 添加自我介绍的行为
Person.metaClass.introduce << {println "I'm $name"}
// 添加性别属性,默认为男(Male)
Person.metaClass.sex = "Male"
def person = new Person(name:"山风小子")
person.introduce()
println person.sex
Run Result:
I ' m a mountain boy
Male