使用 MetaClass 注入构造方法 , 代码格式为 :
被注入构造方法的类.metaClass.constructor = { 闭包 }
为如下 Student 类 , 注入构造函数 , 传入 String 类型的参数 , 赋值给 name 成员 ;
class Student {
def name;
def hello() {
println "Hello $name"
}
}
注入构造函数代码如下 : 构造函数的函数名必须是 constructor ;
// 注入构造函数
// 方法名必须是 constructor
Student.metaClass.constructor = {
String str ->
new Student(name: str)
}
注意 , 构造函数的返回值必须是 Student 对象 ; 这里在注入的构造函数闭包中 , 可以设置若干构造函数参数 , 上述代码中 , 就为构造函数设置了 String 类型参数 ;
使用上述注入的构造函数 , 实例化 Student 对象 , 调用 hello 方法 , 可以成功打印出构造函数中传入的 “Tom” 参数 ;
// 使用注入的构造方法初始化 Student 类
def student = new Student("Tom")
student.hello()
完整代码示例 :
class Student {
def name;
def hello() {
println "Hello $name"
}
}
// 注入构造函数
// 方法名必须是 constructor
Student.metaClass.constructor = {
String str ->
new Student(name: str)
}
// 使用注入的构造方法初始化 Student 类
def student = new Student("Tom")
student.hello()
执行结果 :
Hello Tom