Groovy实现调度DSL如何支持无引号字符串参数调用?
Groovy 无引号DSL实现方案
你可以通过Groovy的两个原生特性实现需求:
- 重写
propertyMissing方法:捕获所有未定义的属性访问请求,直接返回属性名对应的字符串 - 配置闭包解析策略为
DELEGATE_FIRST:让闭包优先从你指定的delegate(Scheduler实例)上查找属性/方法,而非优先从闭包所有者(这里就是测试类)查找
修正后的Scheduler类代码
class Scheduler { String type def static create(closure) { Scheduler scheduler = new Scheduler() closure.delegate = scheduler // 新增:设置闭包优先使用delegate解析属性和方法 closure.resolveStrategy = Closure.DELEGATE_FIRST closure() return scheduler.print_values() } def schedule(String type) { this.type = type } def print_values() { return "${this.type} scheduled" } // 新增:捕获所有未定义的属性访问,直接返回属性名字符串 def propertyMissing(String name) { return name } }
实现逻辑说明
- 当你在闭包里写
schedule meeting时,Groovy会按以下流程执行:- 闭包优先在Scheduler实例上查找
meeting属性 - 未找到对应属性时触发
propertyMissing方法,直接返回属性名"meeting"字符串 - 字符串自动作为参数传入
schedule方法完成赋值
- 闭包优先在Scheduler实例上查找
- 该实现无需提前定义任何调度类型变量,支持任意调度类型直接使用,比如
schedule appointment、schedule interview都可以直接生效,不需要额外修改代码。
内容的提问来源于stack exchange,提问作者Echo C
相关产品推荐
相关产品推荐

