前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Groovy】MOP 元对象协议与元编程 ( 方法委托 | 使用 @Delegate 注解进行方法委托 )

【Groovy】MOP 元对象协议与元编程 ( 方法委托 | 使用 @Delegate 注解进行方法委托 )

作者头像
韩曙亮
发布2023-03-30 11:04:14
4000
发布2023-03-30 11:04:14
举报
文章被收录于专栏:韩曙亮的移动开发专栏

文章目录

一、使用 @Delegate 注解进行方法委托


在博客

中 , 都是通过手动方式实现了方法委托 , Groovy 中提供了 @Delegate 注解可以直接通过一行代码实现方法委托 ;

Delegate 注解原型如下 : 该注解保留到运行时 , 作用于字段上 ;

代码语言:javascript
复制
@java.lang.annotation.Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.DelegateASTTransformation")
public @interface Delegate {
}

在被委托对象上 , 直接使用 @Delegate 注解 , 就可以实现方法委托 ;

代码语言:javascript
复制
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 方法 ;

二、完整代码示例


完整代码示例 :

代码语言:javascript
复制
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()

/*
    方法委托 : 如果调用的某个对象方法没有定义该对象 , 则可以将该方法委托给内部对象执行
 */

执行结果 :

代码语言:javascript
复制
hello1
hello2
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-02-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、使用 @Delegate 注解进行方法委托
  • 二、完整代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档