zl程序教程

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

当前栏目

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

方法对象编程协议 进行 注解 Groovy 委托
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

在这里插入图片描述