zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入构造方法 )

方法注入对象编程协议 进行 Groovy 构造方法
2023-09-14 09:07:29 时间





一、使用 MetaClass 注入构造方法



使用 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

在这里插入图片描述