【Groovy】MOP 元对象协议与元编程 ( 方法委托 | 使用 @Delegate 注解进行方法委托 )
2023-09-14 09:07:28 时间
一、使用 @Delegate 注解进行方法委托
在博客
中 , 都是通过手动方式实现了方法委托 , Groovy 中提供了 @Delegate 注解可以直接通过一行代码实现方法委托 ;
Delegate 注解原型如下 : 该注解保留到运行时 , 作用于字段上 ;
@java.lang.annotation.Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.DelegateASTTransformation")
public @interface Delegate {
}
在被委托对象上 , 直接使用 @Delegate 注解 , 就可以实现方法委托 ;
class Student1{
def hello1(){
println "hello1"
}
}
class Student2{
def hello2(){
println "hello2"
}
}
class StudentManager{
@Delegate Student1 student1 = new Student1()
@Delegate Student2 student2 = new Student2()
}
当调用 StudentManager 对象的 hello1 方法时 , 其没有实现 hello1 方法 , 但是被 @Delegate 注解修饰的 Student1 student1 对象中定义了 hello1 方法 , 此时就会自动进行方法委托 , 调用 student1 对象的 hello1 方法 ;
二、完整代码示例
完整代码示例 :
class Student1{
def hello1(){
println "hello1"
}
}
class Student2{
def hello2(){
println "hello2"
}
}
class StudentManager{
@Delegate Student1 student1 = new Student1()
@Delegate Student2 student2 = new Student2()
}
def sm = new StudentManager()
// 方法委托, 直接通过 StudentManager 对象调用 Student1 中的方法
sm.hello1()
// 方法委托, 直接通过 StudentManager 对象调用 Student2 中的方法
sm.hello2()
/*
方法委托 : 如果调用的某个对象方法没有定义该对象 , 则可以将该方法委托给内部对象执行
*/
执行结果 :
hello1
hello2
相关文章
- 【PHP面向对象(OOP)编程入门教程】17.克隆对象__clone()方法
- Js基础知识7-JavaScript所有内置对象属性和方法汇总
- 在Python中操作文件之truncate()方法的使用教程
- SAP CL_CRM_BOL_ENTITY单元测试方法
- Android 自定义view 的onFinishInflate方法的用法
- 【Groovy】MOP 元对象协议与元编程 ( 方法委托 | 正常方法调用 | 方法委托实现 | 代码示例 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )
- 【Groovy】MOP 元对象协议与元编程 ( Groovy 类内部和外部分别获取 metaClass | 分析获取 metaClass 操作的字节码 | HandleMetaClass 注入方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 分析使用 MetaClass 进行方法注入前后 mateClass 类型变化 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 同时注入普通方法、静态方法、构造方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入构造方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 使用 MetaClass 进行方法拦截 | 对象上拦截方法 | 类上拦截方法 )
- 【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 参考 Script#evaluate 方法 | 创建 Binding 对象并设置 args 参数 )
- 四种内存泄漏方法总结和比较
- JS对象中的方法的this指向
- 【云原生 | 47】etcdctl客户端的使用方法详解
- 为Jquery类和Jquery对象扩展方法
- python基础===创建大量对象是节省内存方法