【Groovy】MOP 元对象协议与元编程 ( 方法委托 | 使用 @Delegate 注解进行方法委托 )
【摘要】
文章目录
一、使用 @Delegate 注解进行方法委托二、完整代码示例
一、使用 @Delegate 注解进行方法委托
在博客
【Groovy】MOP 元对象协...
一、使用 @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
文章来源: hanshuliang.blog.csdn.net,作者:韩曙亮,版权归原作者所有,如需转载,请联系作者。
原文链接:hanshuliang.blog.csdn.net/article/details/122795092
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)