文章目录
一、使用 Mixin 混合进行方法注入
二、完整代码示例
一、使用 Mixin 混合进行方法注入
----
使用 Mixin 混合进行方法注入 , 为下面的 Student 类注入方法 ;
class...Student {
def name
}
首先 , 定义被注入的方法 , 定义一个类 , 在类中定义被注入的方法 , 这里需要注意 , 被注入的方法没有 self 参数 , 不能访问其本身对象..."Hello ${student.name}"
}
}
然后 , 调用类的 mixin 方法 , 将注入方法所在的类混合进指定的 需要注入方法 的类中 ; 可以直接向 Student 类中混合..., 也可以像 Student.metaClass 中混合 , 二者效果相同 ;
// 将 Hello 类中的方法注入到 Student 类中
Student.mixin(Hello)
最后 , 直接调用被注入的方法..., 这里要注意 , 使用 Student 对象调用 hello 方法时 , 同时需要在参数中 , 也传递一个该对象 ;
// 创建 Student 对象
def student = new Student