【发布时间】:2026-02-14 01:35:05
【问题描述】:
开始掌握一般的闭包和一些常规功能。
给定以下代码:
class Mailer {
void to(final String to) { println "to $to" }
void from(final String from) { println "from $from" }
static void send(Closure configuration) {
Mailer mailer = new Mailer()
mailer.with configuration
}
}
class MailSender {
static void sendMessage() {
Mailer.send {
to 'them'
from 'me'
}
}
}
MailSender.sendMessage()
当您将闭包传递给Mailer.send 方法时,幕后会发生什么?
to 和 from 是否从闭包的角度作为参数传递? Closure 映射了哪些类型?
然后在Mailer.send方法内部,此时Mailer对象调用mailer.with接收configuration对象,对象将它们映射成方法调用。 Groovy 通过反射来做到这一点?
【问题讨论】:
标签: groovy